简体   繁体   中英

Jest mock for clone function

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.

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);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM