Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spyOn global timers like clearInterval or setInterval in jasmine-node tests?

I'm writing tests on my server side code which is in nodejs. The tests are written in jasmine 2. I'm running the tests using grunt-jasmine-nodejs.

The server side code uses the timers like setInterval and clearInterval. I want to spy on these timers and see whether these are called.

Server side code - server.js

exports.socketHandler = function(socket){    
...
getResultsInterval = setInterval(getResults, INITIAL_POLL, onResults);    
getResultsTimeout = setTimeout(function() {               
              clearInterval(getResultsInterval);          
            }, 1 * 60 * 1000);
}

Test

var server = require("../../server");
describe('Test the Server', function(){

beforeEach(function(done)){
....
done();
}

 it ('should be able to clear timers', function(done){
spyOn(global, 'setInterval');
spyOn(global, 'clearInterval');

server.socketHandler(socket);

expect(global.setInterval).toHaveBeenCalled();
expect(global.clearInterval).toHaveBeenCalled();

}

The tests are failing with the message -

Error: Expected spy setInterval to have been called. Error: Expected spy clearInterval to have been called.

But the global object has the setInterval method.

Any help would be appreciated.

Thanks

like image 749
SMahadev Avatar asked Apr 26 '16 15:04

SMahadev


1 Answers

I can't take the credit for this, but this answer was given to me when I asked something similar;

beforeEach(function() {
  timerCallback = jasmine. createSpyObj("setInterval");
  jasmine.clock().install();
});

afterEach(function() {
  jasmine.clock().uninstall();
});

it("causes a timeout to be called", function() {
  setTimeout(function() {
    timerCallback();
  }, 1000);

  expect(setInterval).not.toHaveBeenCalled();

  jasmine.clock().tick(1001);

  expect(setInterval).toHaveBeenCalled();
});
like image 162
Takuhii Avatar answered Nov 07 '22 04:11

Takuhii