Skip to content Skip to sidebar Skip to footer

Jasmine Angular Unit Test 'cannot Read 'property' Of Undefined

I have just started learning angular unit testing. However, this test on a function with http call fails. I have pin pointed the problem but however I am not being able to fix it.

Solution 1:

When your test is run, $httpBackend actually intercepts the $http.get call and assign dummyData to the response as you indicated in

$httpBackend.whenRoute('GET','https://www.reddit.com/r/worldnews/new.json').respond(200, dummyData);

This mocking behavior allows your unit tests to be completed quickly without being reliant on reddit being reachable from your test machine. So in your controller, response.data = {name: 'Umair'} and that object has no child named children.

To fix this, for dummyData, try mimicking the real data a bit more.

Solution 2:

You're returning an object with a property name in your test and you're then trying to access the property data which is undefined.

You should simulate a real response object in your tests, e.g.:

var dummyData = {
  data: {
    children: [ 
    { data: 'foo'}
    ]
  }
};

Solution 3:

You dummyData is not an array, I suppose this could fix the issue, please try with below test

//Testing the getJson function
describe('vm.getJson()', function() {

    it('It should return dummy Data as response and vm.result to be truthy', function() {

        var dummyData = [{ data: 'Umair' }];
        $httpBackend
            .when('GET', 'https://www.reddit.com/r/worldnews/new.json')
            .respond(.respond(
                function() {
                    return [200, dummyData, {}];
                }););

        MainCtrl.getJson();

        $httpBackend.flush();

        expect(MainCtrl.result).toBeTruthy();

    });
});

Solution 4:

You should define undefined variables in component scope:

 beforeEach(async () => {
    fixture = TestBed.createComponent(ExportWizardComponent);
    component = fixture.componentInstance;
    // DEFINE VALUES FOR VARIABLES
    component.patientInfo =  Constants.PROJECT_WIZARD_INFO;
    component.wizardMove = of(null);

    fixture.detectChanges();
  });

  it('should create', async () => {
    expect(component).toBeTruthy();
  });

Post a Comment for "Jasmine Angular Unit Test 'cannot Read 'property' Of Undefined"