jest spy on function code example
Example 1: jest mock reset
test("mockFn.mockReset", () => {
const mockFn = jest.fn().mockImplementation(() => 43);
const MockClass = jest.fn();
new MockClass();
expect(mockFn()).toBe(43);
expect(mockFn.mock.calls).toHaveLength(1);
expect(MockClass.mock.instances).toHaveLength(1);
mockFn.mockReset();
MockClass.mockReset();
new MockClass();
expect(mockFn()).toBeUndefined();
expect(mockFn.mock.calls).toHaveLength(1);
expect(MockClass.mock.instances).toHaveLength(1);
});
Example 2: jest spyon
const spy = jest.spyOn(video, 'play');
const spy = jest.spyOn(video, 'play', 'get');
Example 3: jest mock restore
test("mockFn.mockRestore", () => {
const StringUtils = {
toUpperCase(arg) {
return arg && arg.toUpperCase();
}
};
const spy = jest.spyOn(StringUtils, "toUpperCase").mockImplementation(() => "MOCK");
expect(StringUtils.toUpperCase("arg")).toBe("MOCK");
expect(spy).toHaveBeenCalledTimes(1);
expect(jest.isMockFunction(StringUtils.toUpperCase)).toBeTruthy();
spy.mockRestore();
expect(spy("arg")).toBeUndefined();
expect(jest.isMockFunction(StringUtils.toUpperCase)).not.toBeTruthy();
expect(StringUtils.toUpperCase("arg")).toBe("ARG");
expect(spy).toHaveBeenCalledTimes(1);
});
Example 4: jest spy on class method
class MyClass {
methodOne() {
return 1;
}
methodTwo() {
return 2;
}
}
module.exports = MyClass;
test('spy using class method', () => {
const result = new MyClass()
const spy = jest.spyOn(result, 'methodOne')
result.methodOne()
expect(spy).toHaveBeenCalled()
expect(result.methodOne()).toBe(1)
spy.mockReturnValueOnce(12)
expect(result.methodOne()).toBe(12)
})