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 });
1import randomColor from "randomcolor";
2
3
4jest.mock("randomColor", () => {
5 return {
6 randomColor: () => {
7 return mockColor('#123456');
8 }
9 }
10});
11let mockColor = jest.fn();
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 });
1import Foo from './Foo';
2import Bar from './Bar';
3
4jest.mock('./Bar');
5
6describe('Foo', () => {
7 it('should return correct foo', () => {
8 // As Bar is already mocked,
9 // we just need to cast it to jest.Mock (for TypeScript) and mock whatever you want
10 (Bar.prototype.runBar as jest.Mock).mockReturnValue('Mocked bar');
11 const foo = new Foo();
12 expect(foo.runFoo()).toBe('real foo : Mocked bar');
13 });
14});
15
16
17
1test("mock.calls", () => {
2 const mockFn = jest.fn();
3 mockFn(1, 2);
4
5 expect(mockFn.mock.calls).toEqual([[1, 2]]);
6});
1test("mock.instances", () => {
2 const mockFn = jest.fn();
3
4 const a = new mockFn();
5 const b = new mockFn();
6
7 mockFn.mock.instances[0] === a;
8 mockFn.mock.instances[1] === b;
9});