mikemaccana
mikemaccana

Reputation: 123058

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?

Upvotes: 8

Views: 7346

Answers (2)

Amit Levy
Amit Levy

Reputation: 1183

I had the same issue and solved my problem using setupFiles.

Create a jest.config.js file:

const config = {
  setupFiles: ['./src/setupFiles.js']
}

export default config

Then you can write your shared mocks in setupFiles.js

import { Logger } from 'from-some-package'

jest.spyOn(Logger, 'init').mockImplementation(() => jest.fn())
jest.spyOn(Logger, 'info').mockImplementation(() => jest.fn())
jest.spyOn(Logger, 'debug').mockImplementation(() => jest.fn())
jest.spyOn(Logger, 'error').mockImplementation(() => jest.fn())

jest.mock('third-party-package');

global.fetch = jest.fn()

Upvotes: 1

Varun Sharma
Varun Sharma

Reputation: 1752

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.

Upvotes: 4

Related Questions