Jasmine spy training
Different methods for training spies
HTML
<script src="https://jasmine.github.io/2.4/lib/jasmine.js"></script>
<script src="https://jasmine.github.io/2.4/lib/jasmine-html.js"></script>
<script src="https://jasmine.github.io/2.4/lib/boot.js"></script>
<link rel="stylesheet" href="https://jasmine.github.io/2.4/lib/jasmine.css">
JavaScript
"use strict";
describe("spy training", () => {
describe("callThrough", () => {
it("calls the original function", () => {
// Source
let add = (x, y) => {
return x + y;
};
const calculator = {
'add': add
};
// Test
// Before spying
expect(calculator.add(3, 4)).toBe(7);
let spy = spyOn(calculator, 'add');
// Before training - spies return undefined
expect(calculator.add(3, 4)).toBeUndefined();
expect(calculator.add.calls.count()).toBe(1);
// After training - calls original function, still spies execution
spy.and.callThrough();
expect(calculator.add(3, 4)).toBe(7);
expect(calculator.add.calls.count()).toBe(2);
});
});
describe("returnValue", () => {
it("returns predefined values", () => {
// Source
let add = (x, y) => {
return x + y;
};
const calculator = {
'add': add
};
// Test
// After training - returns predefined value
spyOn(calculator, 'add');
calculator.add.and.returnValue(80);
expect(calculator.add(3, 4)).toBe(80);
expect(calculator.add.calls.any()).toBeTruthy();
});
});
describe("callFake", () => {
it("calls a stub function instead of the original one", () => {
// Source
let add = (x, y) => {
return x + y;
};
const calculator = {
'add': add
};
// Test
// After training - calls the fake function
let spy = spyOn(calculator, 'add');
spy.and.callFake((x, y) => {
return x * y;
});
expect(calculator.add(3, 4)).toBe(12);
expect(spy.calls.argsFor(0)).toEqual([3, 4]);
});
});
describe("throwError", () => {
it("throws an error instead of the original one", () => {
// Source
let add = (x, y) => {
return x + y;
};
const calculator = {
'add': add
};
// Test
// After training -...