Unexpected request error when unit-testing angular $http service

739 Views Asked by At

I'm using unit-testing in my angularJS application. Here's a test spec I have for a service:

describe('service', function () {
    var service = {};
    var $httpBackend;

    beforeEach(module('myApp'));
    beforeEach(inject(function (_service_, _$httpBackend_) {
        service = _service_;
        $httpBackend = _$httpBackend_;
    }));

    it('should return test message', function () {
        var response;
        var test = "This is a test";

        $httpBackend.when('GET', '/api/Account/GetTest')
            .respond(200, test);

        service.getTest().then(function (data) {
            response = data;
        });

        expect(response).toEqual(test);
    });
});

And, here's the getTest function in my service:

var getTest = function () {
    return $http.get("api/Account/GetTest");
};

Why am I getting the following error:

Error: Unexpected request: GET api/Account/GetTest

I also figured if I remove the slash from the url in my spec, the error will change to this (and I have no idea why):

Error: Unexpected request: GET /app/views/login.html

1

There are 1 best solutions below

4
Andrew Eisenberg On

The correct test would be to remove the slash. The error that you get then:

Error: Unexpected request: GET /app/views/login.html

implies that angular is trying to download a template unexpectedly. But, since you are using the mock $http, you are getting an error because of the unexpected request.

You could add something like this:

$httpBackend.when('GET', '/app/views/login.html')
        .respond(200, '');

And the error might go away, but:

  1. This may uncover other unexpected template retrievals
  2. Your test is showing unexpected behavior and is therefore unlikely to be small enough to be considered a unit test.

I would recommend that you look through your code and figure out why the login template is being loaded (most likely, you are inadvertently loading a directive or component). Then you can determine if it should indeed be part of the test, or if you should stub it out somehow.

You may need to do this for other templates as well.