JAY PRAKASH
JAY PRAKASH

Reputation: 19

How to mock fetch calls for two different fetch calls and give custom data as a parameter to both of them?

I've 2 different fetch calls in my component


const fetchPopularCuisines = async() => {
    const data = await fetch(URL2)
    const jsonData = await data.json()
    setPopularCuisines(jsonData?.data?.cards[1])
}

const fetchSuggestions = async() =>{
    const data = await fetch(URL1)
    const jsonData = await data.json() 
    setSearchResults(jsonData?.data?.suggestions)
}

I'm trying to test my component using RTL, and the code is as follows:

// POPULAR_CUISINES_DATA is the data which the API gives when I call fetchPopularCuisines()

global.fetch = jest.fn(()=>{
    return Promise.resolve({
        json : () => Promise.resolve(POPULAR_CUISINES_DATA)
    })
})

// testing the code for the first function above[fetchPopularCuisines()]
test('popular cuisines should render after making an API call', async ()=>{

    const searchBar = render(
        <Provider  store={store}>
            <SearchBar />
        </Provider>
    )
    await waitFor(()=>{
        const cuisinesList = searchBar.getAllByTestId('cuisines-list')
        expect(cuisinesList.length).toBe(12)
    } )

})

Until above everything works fine. Now, testing the code for the second function [fetchSuggestions()] breaks the code as I am not sure how to provide different data to the fetch call instead of POPULAR_CUISINES_DATA. I would like to pass the variable SEARCH_RESULTS_DATA for the second fetch call's mock.

How do i do that?

Basically if I have 'n' number of different fetch calls, how do I mock them and provide custom data to Promise.resolve() in each case?

Upvotes: 0

Views: 2573

Answers (1)

pjaoko
pjaoko

Reputation: 71

You could mock the actual implementation of the fetch function as described here: https://jestjs.io/docs/mock-functions#mock-implementations

Some more thorough examples are in this blog post: https://kentcdodds.com/blog/stop-mocking-fetch

You should end up with something like:

async function mockFetch(url, config) {
  switch (url) {
    case URL2: {
      return Promise.resolve({
        json : () => Promise.resolve(POPULAR_CUISINES_DATA)
      })
    }
    case URL1: {
      return Promise.resolve({
        json : () => Promise.resolve(SEARCH_RESULTS_DATA )
      })
    }
    default: {
      throw new Error(`Unhandled request: ${url}`)
    }
  }
}

beforeAll(() => jest.spyOn(window, 'fetch'))
beforeEach(() => window.fetch.mockImplementation(mockFetch))

Upvotes: 0

Related Questions