Home > Blockchain >  Jest mock for clone function
Jest mock for clone function

Time:01-18

I have a fetch request and I've never been able to parse the json from the response without cloning the response: response.clone().json() for context:

fetch(url) {
   .then((response) => { 
     response.clone().json()
   })
   .((json) => {
     //updates a state from `useState`
     setResponse(json)
   })

I'm 100% new to testing with Jest and testing-library but so far I've set a mock for the fetch function:

useEffect(() => {
  const mockedData = jest.fn(() => [{test: "title"}]);
  global.fetch = jest.fn().mockResolvedValue((mockedData) =>
  Promise.resolve({
      json: () => Promise.resolve(JSON.stringify(mockedData))
  })
  )
}, []);

The test is failing saying: error fetching response: TypeError: response.clone is not a function.
If I remove the mock for global.fetch I get: ReferenceError: fetch is not defined. So it seems like I need to mock all these functions out?

Short of knowing how I can fix that issue with clone I'd be curious if there is another way I can fetch this data without cloning it.

CodePudding user response:

You are correct that you would need to mock all subfunctions, also clone.

But you are also correct that you should not need to clone the data from fetch. Your syntax seems to be a little bit off, and you are not returning the json from your function.

Try this

fetch(url)
    .then((response) => response.json())
    .then((json) => {
        //updates a state from `useState`
        setResponse(json);
    });
  •  Tags:  
  • Related