Don’t use arrow function inside mockImplementation with this (Jest)

When using the arrow function:

1
2
3
4
5
6
7
8
// ...
      someAPI.JWT = jest.fn().mockImplementation(() => {
        this.authorize = jest.fn();
        this.credentials = { access_token: "fake_access_token" };
      });
// ...  
const jwtInstance = someAPI.JWT.mock.instances[0];
console.log(jwtInstance); // mockConstructor

When using function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// ...
      someAPI.JWT = jest.fn().mockImplementation(function () {
        this.authorize = jest.fn();
        this.credentials = { access_token: "fake_access_token" };
      });
// ...
const jwtInstance = someAPI.JWT.mock.instances[0];
console.log(jwtInstance);
/*
    mockConstructor {
      authorize: [Function: mockConstructor] {
        _isMockFunction: true,
        getMockImplementation: [Function (anonymous)],
        mock: [Getter/Setter],
        mockClear: [Function (anonymous)],
        mockReset: [Function (anonymous)],
        mockRestore: [Function (anonymous)],
        mockReturnValueOnce: [Function (anonymous)],
        mockResolvedValueOnce: [Function (anonymous)],
        mockRejectedValueOnce: [Function (anonymous)],
        mockReturnValue: [Function (anonymous)],
        mockResolvedValue: [Function (anonymous)],
        mockRejectedValue: [Function (anonymous)],
        mockImplementationOnce: [Function (anonymous)],
        mockImplementation: [Function (anonymous)],
        mockReturnThis: [Function (anonymous)],
        mockName: [Function (anonymous)],
        getMockName: [Function (anonymous)]
      },
      credentials: { access_token: 'fake_access_token' }
    }
*/

Subscribe to the newsletter

Get a once-per-week email with my latest content. By subscribing to this newsletter you will also be the first to receive last updates of my eBooks and courses.

0 members

Comments 💬