JS:
(function(ns) {
var bar;
function getBar() {
return bar;
}
function setBar(value) {
bar = value;
}
function MyTest() {
bar = 5;
return {
getBar: getBar,
setBar: setBar
}
}
window.MyTest = MyTest;
}(window.MyTest));
Then spec:
describe("call fake test", function () {
var sut;
beforeEach(function () {
sut = new window.MyTest();
spyOn(sut, "getBar").and.callFake(function() {
return 1001;
});
});
it("should return 1001", function () {
expect(sut.getBar()).toBe(1001);
})
});
describe("create spy then force a call", function () {
var sut,
fetchedBar;
beforeEach(function () {
sut = new window.MyTest();
spyOn(sut, "getBar").and.callFake(function() {
return 1001;
});
sut.setBar(123);
fetchedBar = sut.getBar();
});
it("tracks that the spy was called", function () {
expect(sut.getBar).toHaveBeenCalled();
})
it("should return 1001", function () {
expect(sut.getBar()).toBe(1001);
})
});
With line:
fetchedBar = sut.getBar();
I am executing getBar method, then with line:
expect(sut.getBar).toHaveBeenCalled();
I am sure that getBar method is executed, and with line:
expect(sut.getBar()).toBe(1001);
we can see that fake value is returned.
Example download from here.