Mocking React Query Hook in Vitest

huangapple go评论65阅读模式
英文:

Mocking React Query Hook in Vitest

问题

以下是您要翻译的内容:

我的组件

export const Product = () => {
  const navigate = useNavigate()
  const { id } = useParams()
  const { data } = useFetchQueries()
  return (
    <Modal>
      <Box>
        {data.data
          .filter((elem: TableElemType) => elem.id.toString() === id)
          .map((elem: TableElemType) => {
            return <ProductData data={elem} key={elem.id} />
          })}
      </Box>
    </Modal>
  )
}

UseFetchQueries:

export const useFetchQueries = () => {
const fetcher = async () => {
const res = await fetch(https://reqres.in/api/products)
.then((res) => res.json())
.then((data) => {
return data
})
.catch((err) => {
return err.message
})
console.log(res)
return res
}
return useQuery(['products'], async () => fetcher())
}


我想在Vitest中测试它,并模拟从useFetchQueries接收到的数据。如何做?

我做了类似这样的事情,但我不知道如何将这个模拟实现到我的组件中。

vi.mock('./useFetchQueries', () => ({
    useFetchQueries: vi.fn().mockReturnValue({ data: { data: ['string'] } }),
}))

describe('ProducData', () => {
    it('if renders proper data', async () => {
        render(renderWithRouter(<Product />, '/5'))
        expect(useFetchQueries).toHaveBeenCalled()
    })
})
英文:

My component:

export const Product = () =&gt; {
  const navigate = useNavigate()
  const { id } = useParams()
  const { data } = useFetchQueries()
  return (
    &lt;Modal&gt;
      &lt;Box&gt;
        {data.data
          .filter((elem: TableElemType) =&gt; elem.id.toString() === id)
          .map((elem: TableElemType) =&gt; {
            return &lt;ProductData data={elem} key={elem.id} /&gt;
          })}
      &lt;/Box&gt;
    &lt;/Modal&gt;
  )
}

UseFetchQueries:

export const useFetchQueries = () =&gt; {
  const fetcher = async () =&gt; {
    const res = await fetch(`https://reqres.in/api/products`)
      .then((res) =&gt; res.json())
      .then((data) =&gt; {
        return data
      })
      .catch((err) =&gt; {
        return err.message
      })
    console.log(res)
    return res
  }
  return useQuery([&#39;products&#39;], async () =&gt; fetcher())
}

I want to test it and mock recieved data from useFetchQueries in Vitest. How to do it?

I did something like this, but I don't know how to implement this mock to my component.

vi.mock(&#39;./useFetchQueries&#39;, () =&gt; ({
    useFetchQueries: vi.fn().mockReturnValue({ data: { data: [&#39;string&#39;] } }),
}))

describe(&#39;ProducData&#39;, () =&gt; {
    it(&#39;if renders proper data&#39;, async () =&gt; {
        render(renderWithRouter(&lt;Product /&gt;, &#39;/5&#39;))
        expect(useFetchQueries).toHaveBeenCalled()
    })
})

答案1

得分: 2

建议的方法是不模拟钩子的结果,而是模拟网络响应:

英文:

The recommended approach is to not mock the result of the hook, but mock the network response:

huangapple
  • 本文由 发表于 2023年1月8日 23:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定