2

I'm using Angular with Angular UI's router. As part of the router configuration, I have a resolve that runs through a few API calls:

$stateProvider.state('someState', {
    templateUrl: '...',
    resolve: {
        auth: someFunction
    },
    controller: 'SomeStateCtrl'
});

someFunction() will do an API call: GET /someAPICall.

Now, say I'm writing a test for some service that has absolutely nothing to do with this state, someFunction(), or GET /someAPICall:

angular.module('app').service('SomeSvc', function () {
    this.something = function () {
        return $http.get('/someOtherCall');
    };
});

describe('SomeSvc Test', function () {
    var SomeSvc, $httpBackend;

    beforeEach(module('app'));

    beforeEach(inject(function (_SomeSvc_, _$httpBackend_) {
        SomeSvc = _SomeSvc_;
        $httpBackend = _$httpBackend_;
    }));

    it('test', function () {
        $httpBackend.whenGET('/someOtherCall').respond({
             example: 'text'
        });

        SomeSvc.something().then(function (data) {
            expect(data.example).toBe('text');
        });

        $httpBackend.flush();
    });
});

As seen above, SomeSvc makes a call to /someOtherCall, but NOT /someAPICall. But when I go to run this unit test, the $httpBackend.flush() ends up trying to process /someAPICall that was spawned from the router:

Error: Unexpected request: GET /someAPICall

Of course I can easily fix this by providing an extra .whenGET in my test to handle /someAPICall, but this doesn't scale. My initial thought was to create some sort of global testing service that handles all of these router API calls (there are more than in my simplified example), so I don't need to redefine them in any of my tests. However, given that I can't seem to find any information on the matter, I feel like something I'm doing is missing the mark and I should be running this a different way.

Any input is appreciated.

3
  • 1
    Just something to consider - using multiple namespaces to create 'sub' modules in your app (like 'app.services') can help simplify situations like this, as you can then load only the relevant module to do your tests, rather than the whole app module which may otherwise cause unnecessary initialisation or require irrelevant dependencies you may then need to manage. Commented Jan 11, 2016 at 22:15
  • @JcT has your best answer. You should try to boot up the smallest module possible for testing. Otherwise expect to add the extra .whenGET. Commented Jan 12, 2016 at 4:39
  • You are bad at javascript - that's the answer. Commented Jan 7, 2019 at 18:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.