Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
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));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!