简体   繁体   中英

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()
  }

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM