Jasmine cheat sheet - mocking the clock
Demonstrating jasmine clock faking functionality
by munir
HTML
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.js"></script>
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine-html.js"></script>
<link rel="stylesheet" href="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.css">
JavaScript
//Munir
describe("Manually ticking the Jasmine Mock Clock", function () {
var timerCallback;
beforeEach(function () {
timerCallback = jasmine.createSpy('timerCallback');
jasmine.Clock.useMock();
});
it("causes a timeout to be called synchronously", function () {
setTimeout(function () {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
// Wait for 150 msec to demonstrate usage of mock clock
waits(150);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.Clock.tick(101);
expect(timerCallback).toHaveBeenCalled();
});
it("causes an interval to be called synchronously", function () {
setInterval(function () {
timerCallback();
}, 100);
expect(timerCallback).not.toHaveBeenCalled();
jasmine.Clock.tick(101);
expect(timerCallback.callCount).toEqual(1);
jasmine.Clock.tick(50);
expect(timerCallback.callCount).toEqual(1);
jasmine.Clock.tick(50);
expect(timerCallback.callCount).toEqual(2);
});
});
// Jasmine spec runner
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var trivialReporter = new jasmine.TrivialReporter();
jasmineEnv.addReporter(trivialReporter);
jasmineEnv.specFilter = function (spec) {
return trivialReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
trivialReporter.outerDiv.className += ' show-passed';
}
})();