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

108
Views
Cannot mock modules inside the test cases

So I have a weird issue where I can't mock modules if they're not on the global scope.

Eg:

// constants.js
exports.SUPPORTED_LANGUAGES = ['en', 'de']
// file-to-test.js
const { SUPPORTED_LANGUAGES } = require('./constants')

exports.asyncFnToTest = async () => {
  const something = SUPPORTED_LANGUAGES.map(() => {
    // do stuff...
  });
}

And here is the catchy part:

// file-to-test.test.js
const { asyncFnToTest } = require('./file-to-test')

it('should test asyncFnToTest', async () => {
  jest.mock('./constants', () => ({
    SUPPORTED_LANGUAGES: ['mock', 'lang'];
  }));
  const { SUPPORTED_LANGUAGES } = require('./constants');

  console.log(SUPPORTED_LANGUAGES); // OUTPUT is: ['en', 'de'] instead of ['mock', 'lang']
});

BUT if the mock is on the global scope like this:

// file-to-test.test.js
const { asyncFnToTest } = require('./file-to-test');
const { SUPPORTED_LANGUAGES } = require('./constants');

jest.mock('./constants', () => ({
    SUPPORTED_LANGUAGES: ['mock', 'lang'];
  }));

it('should test asyncFnToTest', async () => {
  console.log(SUPPORTED_LANGUAGES); // OUTPUT is: ['mock', 'lang']
});

The second approach works okay for functions as I can .mockReturnValue() or .mockImplementation() them, so I can set test scenarios, however SUPPORTED_LANGUAGES is an array so I cannot change the initial mocked value.

Can someone tell me why can't I mock modules inside my test cases or if there's a way to overwrite the array on the global scope for a specific test case?

about 4 years ago · Juan Pablo Isaza
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!