fetch-mock-jest
fetch-mock-jest copied to clipboard
Extend `toHaveFetched` test output to show options diff
Asserting against a certain output, especially a body, is currently very cumbersome.
Scenario: I want to mock a POST request with a specific body, and i want to piece together the body in a test-driven manner.
The assertion only tells us that fetchMock was not called with the right url, which is not even technically correct. This is what it looks like if i pass a wrong body:

The only way to proceed now is to manually console.log the calls i've received with fetchMock.calls() and see where it goes wrong.
In this PR i've extended the output to:
- json-parse the body (if possible)
- use
jest-diffto display the diff between the expected options object and the received options object - for all calls that match the filter
This is what the new output looks like:

@wheresrhys anything missing from this PR?
still waiting on an update here :)
published under [email protected] for preview purposes
published new version with latest jest version under [email protected]
@wheresrhys Any thing we can do to help get this merged in? This would make dealing with assert failures much easier to understand.
Yeah, that's really a pain to distinguish between not-called API and called with a different request payload. Also have spent quite a lot of time just to figure out what's the cause for such an error report.
Updated the fork to newest version of jest, available under [email protected]
new functionality: you're now able to use jest matches in the body you are expecting. for example:
fetch('http://example.com/path', {
method: 'post',
headers: {
test: 'header',
},
body: {
test: {
value: "value"
},
otherValue: {
value: "value"
}
}
})
it("matches when using jest expect matchers", () => {
expect(fetch).toHavePosted('http://example.com/path', {
method: 'post',
headers: {
test: 'header',
},
body: expect.objectContaining({
test: {
value: "value"
}
})
});
})
+1 I was about to start looking into writing this. So nice to see someone has already written the code. What do we need to do to get this merged?