简体   繁体   中英

Having problems unit testing a promise call in angularjs controller

SupportedLanguagesServices get method returns a promise which is resolved in the controller as follows:

    angular.module('App').controller('MyController', ['SupportedLanguagesService',
    function(SupportedLanguagesService) {

        var self = this;
        self.supportedLanguages = [];

        SupportedLanguagesService.get().success(
            function(response) {
                self.supportedLanguages = response;
        });

    }]);

And here is the test I wrote, but it is not working:

    describe('Controller: MyController', function() {

    beforeEach(module('App'));

    var rootScope, controller;

    beforeEach(inject(function($controller, $rootScope, SupportedLanguagesService, $q) {

        var deferred = $q.defer();
        deferred.resolve([{name:"English", code:"en"},{name:"Portugues", code:"pt_BR"]);
        spyOn(SupportedLanguagesService, 'get').andReturn(deferred.promise);

        rootScope = $rootScope;
        controller = $controller;
    }));

    it('should get SupportedLanguages', function() {
        rootScope.$digest();
        var ctrl = controller('MyController');
        expect(ctrl.supportedLanguages.length).toEqual(2);
    });

});

It throws an exception on the statement: var ctrl = controller('MyController');

Thank you for your assistance.

Intead of success (which is an $http callback), you can change to a then , which is available on all promises. This will allow you to easily mock the promise (and not concern yourself with $httpBackend :

    SupportedLanguagesService.get().then(
        function(response) {
            self.supportedLanguages = response.data;
    });

Then, you need to use the controller's constructor and then call a $digest . So, switching to this should get you there:

it('should get SupportedLanguages', function() {

    var ctrl = controller('MyController');
    rootScope.$digest();
    expect(ctrl.supportedLanguages.length).toEqual(2);
});

You can also simplify the setup code using $q.when :

var response = [{name:"English", code:"en"},{name:"Portugues", code:"pt_BR"}];
spyOn(SupportedLanguagesService, 'get').andReturn($q.when(response));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM