1describe("mockImplementation", () => {
2 test("function", () => {
3 const mockFn1 = jest.fn().mockImplementation(() => 42);
4 const mockFn2 = jest.fn(() => 42);
5
6 expect(mockFn1()).toBe(42);
7 expect(mockFn2()).toBe(42);
8 });
1test("es6 class", () => {
2 const SomeClass = jest.fn();
3 const mMock = jest.fn();
4
5 SomeClass.mockImplementation(() => {
6 return {
7 m: mMock
8 };
9 });
10
11 const some = new SomeClass();
12 some.m("a", "b");
13 expect(mMock.mock.calls).toEqual([["a", "b"]]);
14 });
1test("mock.calls", () => {
2 const mockFn = jest.fn();
3 mockFn(1, 2);
4
5 expect(mockFn.mock.calls).toEqual([[1, 2]]);
6});
1//class.js
2class MyClass {
3 methodOne() {
4 return 1;
5 }
6 methodTwo() {
7 return 2;
8 }
9}
10module.exports = MyClass;
11
12// class.test.js
13test('spy using class method', () => {
14 const result = new MyClass()
15 const spy = jest.spyOn(result, 'methodOne')
16 result.methodOne()
17
18 // check class method is call or not
19 expect(spy).toHaveBeenCalled()
20
21 // expect old value
22 expect(result.methodOne()).toBe(1)
23
24 // expect new value
25 spy.mockReturnValueOnce(12)
26 expect(result.methodOne()).toBe(12)
27})