jest-fetch-mock
jest-fetch-mock copied to clipboard
How to create a mock per endpoint
Hey!
Is there a way to mock a endpoint based on what fetch was called with?
Example:
fetch.mockResponseOnce(
"http://api-lsdi.com/api/cart/1",
JSON.stringify(sampleResponse)
);
Basically the intention of this is to say mock this specific endpoint with this payload
Currently there isn't. I'm trying to work through a PR by @yinzara to get this done. You can check out the code here and see if it would fit your usecase:
https://github.com/jefflau/jest-fetch-mock/pull/123
👍 this would be nice
Is it possible to do this with multiple endpoints with the current API? @jefflau
I have fetches to multiple endpoints simultaneously. And I need to mock responses from each of those endpoints dependent on url.
fetch.mockResponse
takes in either the response or a function that accepts the request and generates the response. So you can do exactly like you say by writing a switch statement in the function. Just see the docs or the TypeScript definition.
fetch.mockResponse(request => {
if (request.url.startsWith('http://foo.bar')) {
return /* a response */
} else {
return /* default response */
}
})
Great thanks @yinzara! :D
fetch.mockResponse
takes in either the response or a function that accepts the request and generates the response. So you can do exactly like you say by writing a switch statement in the function. Just see the docs or the TypeScript definition.fetch.mockResponse(request => { if (request.url.startsWith('http://foo.bar')) { return /* a response */ } else { return /* default response */ } })
I've got an error: