How do you spy on AngularJS's $timeout with Jasmine?

て烟熏妆下的殇ゞ 提交于 2019-12-05 07:55:11

In angular $timeout is a service that executes/calls a function. The request to "spy" $timeout is a bit odd being the case that what it is doing is executing X function in Y given time. What I would do to spy this services is to "mock" the timeout function and inject it in your controller something like:

 it('shouldvalidate time',inject(function($window, $timeout){

        function timeout(fn, delay, invokeApply) {
            console.log('spy timeout invocation here');
            $window.setTimeout(fn,delay);
        }

//instead of injecting $timeout in the controller you can inject the mock version timeout
        createController(timeout);

// inside your controller|service|directive everything stays the same 
/*      $timeout(function(){
           console.log('hello world');
            x = true;
        },100); */
        var x = false; //some variable or action to wait for

        waitsFor(function(){
            return x;
        },"timeout",200);

...

Ran into the same problem and ended up decorating the $timeout service with a spy.

beforeEach(module(function($provide) {
    $provide.decorator('$timeout', function($delegate) {
        return sinon.spy($delegate);
    });
}));

Wrote more about why this works here.

This code works for me

var element, scope, rootScope, mock = {
    timeout : function(callback, lapse){
        setTimeout(callback, lapse);
    }
};

beforeEach(module(function($provide) {
    $provide.decorator('$timeout', function($delegate) {
      return function(callback, lapse){
          mock.timeout(callback, lapse);
          return $delegate.apply(this, arguments);
      };
    });
}));
describe("when showing alert message", function(){

    it("should be able to show message", function(){
        rootScope.modalHtml = undefined;
        spyOn(mock, 'timeout').and.callFake(function(callback){
            callback();
        });
        rootScope.showMessage('SAMPLE');

        expect(rootScope.modalHtml).toBe('SAMPLE');

    });

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!