Closed hacknlove closed 1 month ago
I hope you found your solution, but I believe the problem is that your fetchMock
isn't the sandbox from your node-fetch
mock.
Indeed:
// By the magic of babel-jest, this `fetch` is actually a sandbox of the mock
// as defined in the next line.
const fetch = require("node-fetch");
// This mocks "node-fetch" to return a new sandbox for each new require.
// By the magic of babel-jest this runs first thing in this file.
// I also believe that the return value is cached by node, so if several files all do
// `require("node-fetch")` they'll all get the same sandbox -- this is required for all
// this to work.
jest.mock("node-fetch", () => require("fetch-mock-jest").sandbox());
// But _here_ you require from "fetch-mock-jest", _not_ from "node-fetch"
// So you don't get the same object! Instead of getting the mock to "node-fetch",
// you get the mock to the global fetch.
const fetchMock = require("fetch-mock-jest");
describe("bug", () => {
it("should work!", async () => {
// You configure the global mock.
fetchMock.get("/foo", { bar: "buz" });
// but you use the mock to "node-fetch" here.
// So this doesn't work as you expect.
const response = await fetch("/foo").to((r) => r.json());
expect(response).toEqual({ bar: "buz" });
});
The fix is easy: remove the fetchMock
object, and use directly fetch
when you configure it:
const fetch = require("node-fetch");
jest.mock("node-fetch", () => require("fetch-mock-jest").sandbox());
describe("bug", () => {
it("should work!", async () => {
fetch.get("/foo", { bar: "buz" });
const response = await fetch("/foo").then((r) => r.json());
expect(response).toEqual({ bar: "buz" });
});
});
(please note that I also changed an error in the fetch call => you used the function to
which doesn't exist, I replaced it with then
.)
What am I missing here?
https://codesandbox.io/s/bitter-violet-twf31?file=/src/bug.test.js:0-374