Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

110
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda