issue with nock isDone returning false

409 Views Asked by At

I have the following react test:

...

const API_ADDR = "http://localhost:8000";


test("correct response recieved", () =>{
    const {getByText,getByPlaceholderText} = render(<InventoryForm />);
    nock(API_ADDR)
    .post("/inventory", JSON.stringify({ quantity: 2, item_name: "cheesecake" }))
    .reply(200, "Added 2 of item cheesecake!");

  fireEvent.change(getByPlaceholderText("Item name"), {
    target: { value: "cheesecake" }
  });
  fireEvent.change(getByPlaceholderText("Quantity"), {
    target: { value: "2" }
  });
  fireEvent.click(getByText("Add inventory"));
console.log(nock.activeMocks());
  expect(nock.isDone()).toBe(true);

})

But the issues is the expect is returning false:

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      22 |   fireEvent.click(getByText("Add inventory"));
      23 | console.log(nock.activeMocks());
    > 24 |   expect(nock.isDone()).toBe(true);


      at Object.<anonymous> (src/__tests__/itemForm.test.jsx:24:25)

I don't know why this is failing as Im quite new to React testing. I installed "isomorphic-fetch" but I dont know if that has any bearing on the issue. Can someone point me in the right direction? As this issue is holding me up with testing. How nock is supposed to work is that it is just detecting when the button is pressed and then replying with the response defined in the reply right?

1

There are 1 best solutions below

0
On

I experienced this same issue, and here is what I did to resolve it.

React testing library provides an async method waitFor which you can use to ensure that your test waits for the interceptor to be reached. Here is how you can rewrite your test to pass assuming you are using es modules;

import { waitFor } from "@testing-library/react
const API_ADDR = "http://localhost:8000";


test("correct response recieved", async () =>{
    const {getByText,getByPlaceholderText} = render(<InventoryForm />);
    nock(API_ADDR)
    .post("/inventory", JSON.stringify({ quantity: 2, item_name: "cheesecake" }))
    .reply(200, "Added 2 of item cheesecake!");

  fireEvent.change(getByPlaceholderText("Item name"), {
    target: { value: "cheesecake" }
  });
  fireEvent.change(getByPlaceholderText("Quantity"), {
    target: { value: "2" }
  });
  fireEvent.click(getByText("Add inventory"));

  if (!nock.isDone()) {
     console.log(nock.pendingMocks()) // this will log your pending mock
  }
  
  await waitFor(() => expect(nock.isDone()).toBe(true)); // Waits for the interceptor to be reached

})
  1. Note that I used async function to enclose our test block
  2. I used await to wait for waitFor function, which is an async method provided by react testing library. This waits for the interceptor to be reached, and will resolve the issue you are facing.

Hope this helps.