Jasmine cheat sheet - spy matchers
Demonstrating Jasmine spy matchers
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
JavaScript
describe("A spy", function () {
var foo, bar = null;
beforeEach(function () {
foo = {
setBar: function (value) {
bar = value;
}
};
spyOn(foo, 'setBar');
foo.setBar(123);
foo.setBar(456, 'another param');
console.log('foo.setBar.calls ', foo.setBar.calls);
});
it("tracks that the spy was called", function () {
expect(foo.setBar).toHaveBeenCalled();
});
it("tracks its number of calls", function () {
expect(foo.setBar.calls.length).toEqual(2);
});
it("tracks all the arguments of its calls", function () {
expect(foo.setBar).toHaveBeenCalledWith(123);
expect(foo.setBar).toHaveBeenCalledWith(456, 'another param');
});
it("allows access to the most recent call", function () {
expect(foo.setBar.mostRecentCall.args[0]).toEqual(456);
});
it("allows access to other calls", function () {
expect(foo.setBar.calls[0].args[0]).toEqual(123);
});
it("stops all execution on a function", function () {
expect(bar).toBeNull();
});
it("simulates throwing exceptions", function () {
foo.setBar.reset();
foo.setBar.andThrow(new Error('my exception'));
expect(function () {
foo.setBar()
}).toThrow();
});
it("can be retrained", function () {
foo.setBar.reset();
foo.setBar.andReturn('first');
expect(foo.setBar()).toEqual('first');
foo.setBar.andReturn('second');
expect(foo.setBar()).toEqual('second');
});
});
// 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;
...