'Get rid of duplicate jest.mock

Using the same jest.mock, returning different results, leads to the accumulation of duplicate code.

I did not find information on how to deal with this and I would like to ask if it is possible to create a function similar to the following:

const createMock = (result) => jest.mock('some-module', () => (result));


Solution 1:[1]

No, It is Immpossible. You should always write a new mock at the top of describe

Solution 2:[2]

You can use jest.mock() in the module scope of the test file. It will be hoisted to the top of the file before any import. Which means the imported module is already mocked. So that you can use mock.mockReturnValue() method in each test case to provide a different return value.

E.g.

index.js:

import someFn from './some-module';

export default function main() {
  return someFn();
}

some-module.js:

export default function someFn() {
  return 'a';
}

index.test.js:

import main from './';
import someFn from './some-module';

jest.mock('./some-module');

describe('71219584', () => {
  test('should pass 1', () => {
    someFn.mockReturnValue('fake a');
    console.log(main());
  });
  test('should pass 2', () => {
    someFn.mockReturnValue('fake b');
    console.log(main());
  });
});

Test result:

 PASS  stackoverflow/71219584/index.test.js
  71219584
    ? should pass 1 (17 ms)
    ? should pass 2 (2 ms)

  console.log
    fake a

      at Object.<anonymous> (stackoverflow/71219584/index.test.js:18:13)

  console.log
    fake b

      at Object.<anonymous> (stackoverflow/71219584/index.test.js:22:13)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.186 s

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DTR
Solution 2 slideshowp2