开玩笑模拟克隆功能

Jest mock for clone function

我有一个提取请求,但我一直无法在不克隆响应的情况下从响应中解析 json:response.clone().json() for context:

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

我对使用 Jest 和测试库进行测试 100% 陌生,但到目前为止,我已经为 fetch 函数设置了一个模拟:

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

测试失败说:error fetching response: TypeError: response.clone is not a function
如果我删除 global.fetch 的 mock,我会得到:ReferenceError: fetch is not defined。所以我似乎需要模拟所有这些功能?

不知道如何用 clone 解决这个问题我很好奇是否有另一种方法可以在不克隆的情况下获取这些数据。

你说得对,你需要模拟所有子函数,也需要克隆。

但是您也说得对,您不需要从 fetch 中克隆数据。您的语法似乎有点偏离,并且您没有从函数中返回 json。

试试这个

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