fetch-mock-jest icon indicating copy to clipboard operation
fetch-mock-jest copied to clipboard

Extend `toHaveFetched` test output to show options diff

Open tobilen opened this issue 4 years ago • 8 comments

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: image

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-diff to 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: image

tobilen avatar Mar 04 '21 12:03 tobilen

@wheresrhys anything missing from this PR?

tobilen avatar Mar 10 '21 10:03 tobilen

still waiting on an update here :)

tobilen avatar May 17 '21 14:05 tobilen

published under [email protected] for preview purposes

tobilen avatar Jun 04 '21 15:06 tobilen

published new version with latest jest version under [email protected]

tobilen avatar Aug 20 '21 10:08 tobilen

@wheresrhys Any thing we can do to help get this merged in? This would make dealing with assert failures much easier to understand.

petersendidit avatar Nov 04 '21 21:11 petersendidit

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.

theghostbel avatar Feb 07 '22 13:02 theghostbel

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"
			}
		})
	});
})

tobilen avatar Jul 21 '22 14:07 tobilen

+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?

macdonaldr93 avatar Nov 22 '22 16:11 macdonaldr93