Search code examples
javascripttypescriptunit-testingjestjs

How can I share jest mocks between multiple tests?


I have a mock version of the aws-sdk, which works fine in my tests:

jest.mock("aws-sdk", () => {
  return {
    Credentials: jest.fn().mockImplementation(() => ({})),
    Config: jest.fn().mockImplementation(() => ({})),
    config: {
      update: jest.fn(),
    },
    S3: jest.fn().mockImplementation(() => ({
      getSignedUrlPromise: awsGetSignedUrlMock,
    })),
    SQS: jest.fn().mockImplementation(() => ({})),
  };
});

However many of my tests use the mock AWS SDK, and I would like to not repeat the mock code unnecessarily. If I move the function into a separate file and import it, however, this will fail:

In my testSupport.ts file:

export const mockAwsSdk = () => {
  return {
    Credentials: jest.fn().mockImplementation(() => ({})),
    Config: jest.fn().mockImplementation(() => ({})),
    config: {
      update: jest.fn(),
    },
    S3: jest.fn().mockImplementation(() => ({
      getSignedUrlPromise: awsGetSignedUrlMock,
    })),
    SQS: jest.fn().mockImplementation(() => ({})),
  };
};

In the test file:

jest.mock("aws-sdk", mockAwsSdk);

This fails with:

ReferenceError: Cannot access 'testSupport_1' before initialization

I have tried various solutions, including making a parent function that takes the jest instance, but I still haven't been able to get this to work.

How can I share jest mocks between multiple tests?


Solution

  • Jest has a moduleNameMapper config property which can be used to specify a string or regular expression to match your import and replace it with a mock file

    Alternatively, you can add mocks without specifying it in the moduleNameMapper by placing your mock file in a folder named __mocks__ which should be in the same directory as the file you need to mock

    In case it is in node_modules, the __mocks__ folder should be in your parent directory.