Sachin Mhaskar
Sachin Mhaskar

Reputation: 5

Not getting json response from unit test in karma jasmine in angularjs?

describe('getEmployeeDetails', function () {
var getEmployeeDetails, httpBackend;
//2.
beforeEach(function () {
    //3. load the module.
    module('nodeApp');

    // 4. get your service, also get $httpBackend
    // $httpBackend will be a mock.
    inject(function ($httpBackend, _getEmployeeDetails_) {
        getEmployeeDetails = _getEmployeeDetails_;
        httpBackend = $httpBackend;
    });
});

// 5. make sure no expectations were missed in your tests.
afterEach(function () {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});

//6.
it('ServiceTestSpec', function () {

    var returnData = {};

    //7. expectGET to make sure this is called once.
    httpBackend.expectGET("/employee/getEmployeeDetails").respond(returnData);

    //8. make the call.
    var returnedPromise = getEmployeeDetails.getEmployees();

    //9. set up a handler for the response, that will put the result
    // into a variable in this scope for you to test.
    var result;
    returnedPromise.then(function (response) {
        result = response.data;
    });

    //10. flush the backend to "execute" the request to do the expectedGET assertion.
    httpBackend.flush();

    //11. check the result.
    expect(result).toEqual(returnData);
});

Here is my unit test written in karma jasmine. I am debugging this unit test in chrome console, but I am getting "response" object blank.

I used $httpBackend to fake the HTTP request. Is that the reason I am not getting the response object?

But I am getting the test pass SUCCESS. And one more thing is: Is this the good practice? To write the unit test in angularJS?

Upvotes: 0

Views: 585

Answers (1)

yclee0210
yclee0210

Reputation: 131

By default angularJS Karma tests block $http requests, so you would not get the json response. To get the response, instead of attaching .respond(yourFakeResponse), use .passThrough(), which will make the intended request.

However, in my opinion this is not really a good practice, as the test now depends on external resource, i.e. your json file in this case, or any other external API etc. As issues in the external resource can also break the test, this no longer falls in the category of unit tests, and is more of an integration test.

It would be better to, as you have done, call a fake response object, whilst setting up a separate constant or service file to centralize the management of your mock response data.

Upvotes: 0

Related Questions