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
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With