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

1

6

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

Outpour answered 26/4, 2016 at 15:39 Comment(0)
N
1

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();
});
Nosey answered 18/6, 2018 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.