Jest change mock implementation for a POJO module between tests

Tags: , ,



I am trying to mock the import of a Plain Old Javascript Object in a test, where I want different implementations for each test.

If I mock at the top of the file it works as expected:

import { getConfig } from './'; // this contains the import config from 'configAlias';

jest.mock('configAlias', () => ({
  hello: 'world',
}));

it('passes test', () => {
  expect(getConfig()).toEqual({
    hello: 'world,
  });
});

But I cannot find any combination of doMock, default over named exports, mockImplementation to get the following to work:

import { getConfig } from './'; // this contains the import config from 'configAlias';


it('fails test1', () => {
  jest.doMock('configAlias', () => ({
    hello: 'world',
  }));
  const config = require('configAlias');

  expect(getConfig()).toEqual({
    hello: 'world,
  });
});

it('fails test2', () => {
  jest.doMock('configAlias', () => ({
    hello: 'moon',
  }));
  const config = require('configAlias');

  expect(getConfig()).toEqual({
    hello: 'moon,
  });
});

Edit 1

Based on @jonrsharpe I have tried

import { getConfig } from './'; // this contains the import config from 'configAlias';

const mockConfig = jest.fn();
jest.mock('configAlias', () => mockConfig);

it('fails test', () => {
  mockConfig.mockImplementation({
    hello: 'world',
  });
  expect(getSchema()).toEqual({ hello: 'world' });
});

Answer

Worked it out, the trick is to import/require the file under test (not the mocked file) AFTER setting the mock in the individual test. No import at the top of the file.

beforeEach(() => {
  jest.resetModules();
});

it('passes test 1', () => {
  jest.mock('configAlias', () => ({
    hello: 'world',
  }));
  const { getConfig } = require('getConfig');

  expect(getConfig()).toEqual({
    hello: 'world',
  });
});

it('passes test 2', () => {
  jest.mock('configAlias', () => ({
    hello: 'moon',
  }));
  const { getConfig } = require('getConfig');

  expect(getConfig()).toEqual({
    hello: 'moon',
  });
});


Source: stackoverflow