jest mock constructor mockimplementation code example
Example 1: jest mock class
test("es6 class", () => {
const SomeClass = jest.fn();
const mMock = jest.fn();
SomeClass.mockImplementation(() => {
return {
m: mMock
};
});
const some = new SomeClass();
some.m("a", "b");
expect(mMock.mock.calls).toEqual([["a", "b"]]);
});
Example 2: jest mock implementation
describe("mockImplementation", () => {
test("function", () => {
const mockFn1 = jest.fn().mockImplementation(() => 42);
const mockFn2 = jest.fn(() => 42);
expect(mockFn1()).toBe(42);
expect(mockFn2()).toBe(42);
});
Example 3: 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)
})