3

After a bit of trial and error I finally managed to get Jasmine to inject a mock Angular service and also provide $httpBackend in the same suite:

describe('services.system', function () {

    var httpBackend, nodeService;

    beforeEach(module('services.system'));

    beforeEach(function() {
        module(function($provide) {
            $provide.factory('authService', function() { return mockAuthService; });
        });

        inject(function(_nodeService_, $httpBackend) {
            httpBackend = $httpBackend;
            nodeService = _nodeService_;
        });
    });

    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation();
        httpBackend.verifyNoOutstandingRequest();
    });

    describe('version', function () {
        it('should return the current version', function () {
            httpBackend.expectGET('/service/version').respond(200, { version: "1.2.3"});

            var done = false;
            runs(function() {
                nodeService.getProductInfo().then(function (info) {
                    expect(info.version).toEqual('1.2.3');
                    done = true;
                }, function(error) {
                    expect("test received error: " + error).toFail();
                    done = true;
                });

                httpBackend.flush();
            });

            waitsFor(function(){
                return done;
            });
        });
    });
});

I now want to write a test that expects a GET only once, two consecutive calls should return a cached response and not make another request to the server. With spies it looks like you can usually do this by asserting myObj.calls.count().

How might I verify that the HTTP request has only been invoked once?

seanhodges
  • 17,426
  • 15
  • 71
  • 93
  • If caching is not something that you have implemented, but is part of framework, then no point testing it. No point testing the framework. – Chandermani Dec 30 '14 at 09:28
  • Good point. I am storing the result in a variable, so the next call to getProductInfo() should be fetching from memory rather than performing another HTTP request. – seanhodges Dec 30 '14 at 09:42
  • 3
    `expectGET` has to be setup for each request I believe. So if you have only on `expectGET` in your test, and the test passes, there was only one request made. – Chandermani Dec 30 '14 at 09:54

0 Answers0