jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
883 stars 116 forks source link

How to create a mock per endpoint #126

Open kennetpostigo opened 5 years ago

kennetpostigo commented 5 years ago

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

jefflau commented 5 years ago

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

benmonro commented 4 years ago

👍 this would be nice

Marvedog commented 4 years ago

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.

yinzara commented 4 years ago

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 */
   }
})
Marvedog commented 4 years ago

Great thanks @yinzara! :D

namlq93 commented 3 years ago

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