Jasmine Spy Matchers: toHaveBeenCalled(), toHaveBeenCalledWith(), toHaveBeenCalledTimes()
In this tutorial, we illustrate the workings of the
toHaveBeenCalled(),
toHaveBeenCalledWith() and
toHaveBeenCalledTimes() spy matchers.
We consider the constructor function below
function Circle() {
this.circumference = function(r) {
return 2*Math.PI*r;
}
};
toHaveBeenCalled() Matcher
The toHaveBeenCalled() matcher verifies
whether the spied method has been called or not. It returns
true if the spy was called. The
following spec returns true as the method
circumference() is called
describe("The 'toHaveBeenCalled' spy matcher", function() {
it('should track that the spy was called', function() {
var c = new Circle();
spyOn(c,'circumference');
c.circumference(2);
expect(c.circumference).toHaveBeenCalled();
});
});
toHaveBeenCalledWith() Matcher
The toHaveBeenCalledWith() matcher
verifies whether the spied method has been called with the right
argument(s). It returns true if there
has been any one call with the matching argument(s). In the spec
below, the circumference() method is
called upon by passing the argument 2. The
toHaveBeenCalledWith() matcher returns
true and the spec passes
describe("The 'toHaveBeenCalledWith' spy matcher", function() {
it('should track the arguments of its calls', function() {
var c = new Circle();
spyOn(c,'circumference');
c.circumference(2);
expect(c.circumference).toHaveBeenCalledWith(2);
});
});
toHaveBeenCalledTimes() Matcher
The toHaveBeenCalledTimes() matcher
verifies whether the spied method has been called a specified number
of times (which is passed as an argument). In the following spec,
the circumference() method is called
upon once. The
toHaveBeenCalledTimes() matcher is
passed the number 1 as an argument, to
which it returns true, and the spec
passes.
describe("The 'toHaveBeenCalledTimes' spy matcher", function() {
it('should track the number of times the spy was called', function() {
var c = new Circle();
spyOn(c,'circumference');
c.circumference(2);
expect(c.circumference).toHaveBeenCalledTimes(1);
});
});