简体   繁体   中英

Unit testing AngularJs with Jasmine: then - catch testing issue

I have a following piece of code (simplified):

angular
.module('myApp')
.controller('MyController', MyController);

function MyController(wordService) {

    getWord();

    function getWord() {

        return wordService.getNextWord()
           .then(doSomethingWithWord)
           .catch(doSomethingFailure);

        function doSomethingWithWord(response) {
            //    ... something
        }

        function doSomethingFailure() {
            //    ... failing
        }
    }
}

And I have to test it. I'm struggling with this over a day now and I can't get it working :(

How to test this code?

For the future, I figured it out: I have to use $q service and request Angular digest cycle.

describe('MyController', function () {

    var $controller, myController, wordService, $q, deferredResponse, scope;

    beforeEach(function() {
        module('myApp');
        inject(function(_$controller_, _wordService_, _$q_, $rootScope) {
            $controller = _$controller_;
            wordService = _wordService_;
            scope = $rootScope.new();
            $q = _$q_;
        });
        myController = $controller('MyController', {wordService:wordService});

        deferredResponse = $q.defer(); //deferring asynchronous response
        spyOn(wordService, 'getNextWord').and.returnValue(deferredResponse.promise);
    });

    describe('Testing WordService', function() {
        it('Should get next word', function () {
            deferredResponse.resolve({status: 200, data: {word: 123}});
            scope.$apply();

            expect(wordService.getNextWord).toHaveBeenCalled();
        })
    })
});

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