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

131
Visualizações
Jest not mocking functions properly

So I have a module called A with two functions:

function handleCreatedOrder(){
  console.log("here")
}

function acquireOrder(){
  if(condition) handleCreatedOrder
}

I have a test which needs to check if handleCreatedOrder is getting called. I have mocked the module by first importing the module import * as acquireOrderWrapper from './module'

Then in the test I am spying on the module by let handleCreatedOrderSpy = jest.spyOn(acquireOrderWrapper, "handleCreatedOrder")

When I try to assert expect(handleCreatedOrder).toBeCalled() it fails because the received number of calls does not match. I understand this is because the mocking is not proper as the console.log from handleCreatedOrder is called but the expect statement fails. What am I doing wrong?

My tests are currently like

describe("handle acquireOrder success responses", () => {
  const reactRedux = { useDispatch, useSelector }
  const useDispatchMock = jest.spyOn(reactRedux, "useDispatch")

  test("test1", async () => {
    let handleCreatedOrderSpy = jest.spyOn(acquireOrderWrapper, "handleCreatedOrder")
    await acquireOrder()
    expect(handleCreatedOrderSpy).toBeCalled()
  }
almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I think what you need to do is create a spy on the handleCreatedOrder function first and then call the acquireOrder function inside your test.

The spy will then be called once you execute the acquireOrder function and your test should pass. I usually develop my frontend with angular and typescript but for reactJS it should look similiar.

test('test if function was called', async () => {
  jest.spyOn(component, 'handleCreatedOrder').mockImplementation();
  await acquireOrder();
  expect(component.handleCreatedOrder).toHaveBeenCalled();
}

you might need to add a changeDetector in your test after running the acquireOrder function. In typescript ususally i add fixture.detectChanges after running the function like this

fixture.detectChanges();

Also i noticed you are missing () after your function.

function acquireOrder(){
  if(condition) handleCreatedOrder()
}
almost 4 years ago · Santiago Trujillo 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