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

How to create a mock per endpoint

Open kennetpostigo opened this issue 5 years ago • 6 comments

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

kennetpostigo avatar Jul 22 '19 17:07 kennetpostigo

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

jefflau avatar Jul 23 '19 05:07 jefflau

👍 this would be nice

benmonro avatar Sep 10 '19 16:09 benmonro

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.

Marvedog avatar Jul 28 '20 08:07 Marvedog

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 */
   }
})

yinzara avatar Jul 28 '20 16:07 yinzara

Great thanks @yinzara! :D

Marvedog avatar Jul 30 '20 08:07 Marvedog

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: Screen Shot 2020-10-16 at 13 06 38

namlq93 avatar Oct 16 '20 06:10 namlq93