Closed michielbdejong closed 3 years ago
This is because we test for the presence of a response body with:
fetch.mockIf = fetch.doMockIf = (urlOrPredicate, bodyOrFunction, init) => {
isMocking.mockImplementation(requestMatches(urlOrPredicate))
if (bodyOrFunction) {
fetch.mockResponse(bodyOrFunction, init)
}
return fetch
}
Which returns false
for if (bodyOrFunction)
in the case where you pass an empty string. I guess we could change them to checks for undefined but I really don't think your use case is something we really want to support.
Fair enough! Too bad for us. :)
I'm trying to write a test where I want to check how my code reacts to an empty response body. If that's not supported by jest-fetch-mock then I'll find a different way to mock it.
Are you aware of any other fetch mock libraries we could try out instead for this? Maybe we should just mock fetch manually for this test?
Oh sorry I assumed by posting the code you could see there is a work around but that's stupid to assume so here it is lol:
describe("Conditionally mock empty body", () => {
beforeEach(() => {
fetchMock.mockIf("https://example.com/");
fetchMock.mockResponse("");
});
it("Resolves to empty string", async () => {
const result = await fetchMock("https://example.com/");
const text = await result.text();
expect(text).toEqual("");
});
});
It seems that conditionally mocking an empty response body doesn't always work as expected:
Expected output: all 4 tests pass Actual output: