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

95
Visualizações
Get original implementation during jest mock

I'm trying to temporarily mock node-fetch in an ESM module while still retraining the original implementation so I can access a real endpoint's value. However, this errors with "Must use import to load ES Module." I recognize jest support for ESM is still pending - is there any way to have this behavior in a combination of current Node, ES6, and Jest?

worker.ts (dependency):

export default async () => {
    const response = await fetch("http://example2.org");
    return await response.json()
  }

main.test.ts:

import { jest } from "@jest/globals";


jest.mock("node-fetch", () => {
    return Promise.resolve({
        json: () => Promise.resolve({ myItem: "abc" }),
    })
})

import doWork from './worker.js';
import mockedFetch from 'node-fetch';

const originalFetch = jest.requireActual('node-fetch') as any;

test("Ensure mock", async () => {
    const result = await doWork();
    expect(result.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(1);

    const response = await originalFetch("http://www.example.org");
    expect(response.status).toBe(200);

    const result2 = await doWork();
    expect(result2.myItem).toStrictEqual("abc");
    expect(mockedFetch).toBeCalledTimes(2);
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, Jest doesn't support jest.mock in ESM module for tests

Please note that we currently don't support jest.mock in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow this issue for updates.

This is reasonable because import has different semantic than require. All imports are hoisted and will be evaluated at module load before any module code.

So in your case because you are using jest.mock I assume that your test code are transformed. In this case, if you want to use non "CommonJS" package, you should transform it too. You can change transformIgnorePatterns in jest config to []. It means that all packages from node_modules will go through transform. If it's too aggressive, you can pick specific modules which ignore like this "transformIgnorePatterns": [ "node_modules/(?!(node-fetch))" ] but don't forget about transitive dependencies. ;)

  • Add/change in jest config
  "transformIgnorePatterns": []
  • jest.mock accept module factory which should returns exported code. In your case, you should write it like this.
jest.mock("node-fetch", () => {
  return {
    __esModule: true,
    default: jest.fn(() =>
      Promise.resolve({
        json: () => Promise.resolve({ myItem: "abc" }),
      })
    ),
  };
});

If you have error

The module factory of jest.mock() is not allowed to reference any out-of-scope variables

just remove jest from import and use it as global variable or import it inside the module factory function https://github.com/facebook/jest/issues/2567

  • Change const originalFetch = jest.requireActual('node-fetch') to
const originalFetch = jest.requireActual('node-fetch').default;
about 4 years ago · Juan Pablo Isaza Relatório
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