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

208
Visualizações
Debugging jest mocks

I've got a library that's giving me some trouble in my jest tests.

This library is included throughout my project, and it has an annoyingFunction that has a console.error in it. So, whenever I run a test, I naturally get unwanted console.error messages all over the place.

I don't want to mock out the whole library, just the annoyingFunction, so I put this in my setup file:

jest.mock('myLibrary', () => ({
   ...jest.requireActual('myLibrary'),
   annoyingFunction: jest.fn(),
}));

This is being run, however, the original annoyingFunction is still being called, polluting my tests with console.error calls.

If I console log my mock, I clearly see annoyingFunction: [Function: mockConstructor], so the mock is working, but for some reason, the original function from the library is still being called.

What am I missing here? Is there something wrong with my initial setup of the mock?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There could be a couple of things wrong, but my guess is that annoyingFunction is called internally within the library. Consider the following example, which doesn't do what you might expect it to:

foo.js

function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

function multiply(a, b) {
  let total = 0;
  for (let i = 0; i < b; i++) {
    total = add(total, a);
  }
  return total;
}

export {
  add,
  subtract,
  multiply
};

foo_test.js

import * as Operations from "./foo.js";

jest.mock("./foo.js", () => ({
  ...jest.requireActual("./foo.js"),
  add: () => -999,
}));

describe("all the things", () => {
  // Here, the mock does what you would expect, because you're calling the
  // exported function "add."
  it("can add", () => {
    expect(Operations.add(1, 2)).toEqual(-999);
  });
  it("can subtract", () => {
    expect(Operations.subtract(1, 2)).toEqual(-1);
  });
  // Here, the mock doesn't do what you would expect. because unbeknownst to
  // you, `multiply` calls `add` _within_ the module code.  The mock has no
  // effect in this case.
  it("can multiply", () => {
    expect(Operations.multiply(1, 2)).toEqual(2);
  });
});

I'm not really sure what you can do about this, except to mock exported methods of the library until you can control the result.

Or...you could jest.spyOn console.error for whichever test is giving you a problem, and reset the spy afterward.

const consoleErrorSpy = jest.spyOn(console, "error");
//...do your test...
consoleErrorSpy.mockRestore();

Hope that helps!

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