0
votes

I am still trying to learn Jasmine and test an Angular service. Currently I am trying to test the .success and error calls off http.get.

Service Call

    this.get = function (param1, param2) {

        return $http.get('api/something/get/param1/param2')
            .success(function (data) {
                return data;
            })
            .error(function() {
                return "Please select param1 AND param2";
            });
    };

Jasmine Tests

    it('service makes unsuccessful API call', function() {
        var response = "This is the response";

        httpBackend.when('GET', "api/something/Get/0/0").respond(404);

        var data;

        service.get(0, 0).then(function(result) {
            data = result;
        });

        httpBackend.flush();

        expect(data).toEqual("Please select param1 AND param2");


    });

    it('service makes successful API call', function () {
        var response = "This is the response";
        httpBackend.when('GET', "api/something/Get/0/0").respond(response);
        var data;

        service.get(0, 0).then(function(result) {
            data = result.data;
        });

        httpBackend.flush();

        expect(data).toEqual(response);


    });

In the first test (Error) the data = result.data line in then() is never called. On the expect(data).toEqual(), data is undefined. When I step through everything I see where the service is called and the error message is populated in result.data.

In the second test (Success), I see the same thing but the data is set when the then function is called.

Why is my then function not called on .error()?

1
because you have no rejection handler argument in then(resolveHandler,rejectHandler)charlietfl
Thanks for the help. Adding the rejectHandler solved the problem.James

1 Answers

0
votes

success() and error() don't work the same way as then(). The value returned by the callback is ignored. success() and error() return the promise on which they're called, and not a new promise like then().

So, their usage should be limited to callbacks having side-effects only (like initializing a scope variable).