Jasmine stubs
We have already seen some use cases for Jasmine spies. Remember that a spy is a special function that records how it was called. You can think of a stub as a spy with behavior.
We use stubs whenever we want to force a specific path in our specs or replace a real implementation for a simpler one.
Let's revisit the example of the acceptance criteria, "Stock when fetched, should update its share price", by rewriting it using Jasmine stubs.
We know that the stock's fetch
function is implemented using the $.getJSON
function, as follows:
Stock.prototype.fetch = function(parameters) {
$.getJSON(url, function (data) {
that.sharePrice = data.sharePrice;
success(that);
});
};
We could use the spyOn
function to set up a spy on the getJSON
function with the following code:
describe("when fetched", function() { beforeEach(function() { spyOn($, 'getJSON').and.callFake(function(url, callback) { callback({ sharePrice: 20.18 }); }); stock.fetch(); }); it("should...