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

130
Views
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 answers
Answer question

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 Report
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!