How do you look at AngularJS $ timeout with Jasmine?

I am trying to peek into $ timeout to verify that it was not called. In particular, my production code (see below) calls $ timeout as a function, not an object:

$timeout(function() { ... }) 

but not

 $timeout.cancel() // for instance 

Jasmine, however, requires the object to spy, for example:

 spyOn(someObject, '$timeout') 

I don't know what "someObject" would be.

I use Angular mocks if that matters.

Edit: The corresponding production code that I am trying to verify is as follows:

 EventHandler.prototype._updateDurationInOneSecondOn = function (call) { var _this = this; var _updateDurationPromise = this._$timeout(function () { call.duration = new Date().getTime() - call.startTime; _this._updateDurationInOneSecondOn(call); }, 1000); // ... more irrelevant code } 

In a specific test case, I am trying to argue that $ timeout has never been called.

Edit 2: It is clearly stated that I am using $ timeout as a function, not an object.

+6
source share
3 answers

In angular, $timeout is a service that executes / calls a function. The $timeout request is a little strange if it performs the function X at Y for the given time. What I would do to spy on these services is to "ridicule" the timeout function and enter 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); ... 
+1
source

Go into the same problem and end up stealing the $ timeout service by a spy.

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

Wrote more about why this works here .

+7
source

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'); }); }); 
0
source

Source: https://habr.com/ru/post/959220/


All Articles