Name your mocked function with word "mock"

Let's look at the example:

const fakeApi = jest.fn().mockImplementation(() => ({
  ok({
    data: []
  })
}));

jest.mock('../some-module.js', () => {
  return jest.fn().mockImplementation(function () {
    this.api = fakeApi;
  });
});

It's a part of the test where we mock some module. We also use mocked function "fakeApi" in the mock of module. But it will not work because function "fakeApi" will be in Temporal Dead Zone In JavaScript.

Basically, it happens because all module's mocks in Jest moves on the top of test's executing. So, when test is running, jest.mock('../some-module.js'... is above than mockApi.

We can avoid this behavior. We should name function "fakeApi" with word "mock" at the beginning. Something like that:

const mockApi = jest.fn().mockImplementation(() => ({
  ok({
    data: []
  })
}));

jest.mock('../some-module.js', () => {
  return jest.fn().mockImplementation(function () {
    this.api = mockApi;
  });
});
Share:

About

My name is Max, also known as @mxkvl.

I am a software developer, currently working mostly with TypeScript, React and Node ecosystems.

I write a blog about topics that interest me most: programming languages in general, TypeScript, testing, writing and other great stuff.

Join the Mailing List