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?
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;
Hope this helps.