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

303
Views
How do I mock a primitive value for a single test?

I have a test that requires the value of isBanana to be false.

The test works (and isBanana is false) when I mock the function in the top level index.test.js. However this breaks other tests (as they require isBanana to be true).

jest.mock("myapp-api-functions", () => {
  console.log(`executing mock function`);
  return {
    ...jest.requireActual("myapp-api-functions"),
    isBanana: false,
  };
});

If I move the jest.mock() into the body of the test, isBanana is true and the test doesn't work.

    it(`should error when someone tries to use the mock account in production`, async () => {
      jest.mock("myapp-api-functions", () => {
        console.log(`executing mock function`);
        return {
          ...jest.requireActual("myapp-api-functions"),
          isBanana: false,
        };
      });

      ...same test function that previously passed...
    });

The mock doesn't work and the test fails.

How can I mock the primitive value for a single test?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Calls to jest.mock get hoisted to the top of the code block.

To avoid this behaviour you can instead use jest.doMock e.g.

it(`should error when someone tries to use the mock account in 
production`, async () => {
  jest.doMock("myapp-api-functions", () => {
    console.log(`executing mock function`);
    return {
      ...jest.requireActual("myapp-api-functions"),
      isBanana: false,
    };
  });

  // Same test function that previously passed...
});

This will allow you to specify mock behaviour for a specific test.

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!