英文:
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 = () => {
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())
}
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('./useFetchQueries', () => ({
useFetchQueries: vi.fn().mockReturnValue({ data: { data: ['string'] } }),
}))
describe('ProducData', () => {
it('if renders proper data', async () => {
render(renderWithRouter(<Product />, '/5'))
expect(useFetchQueries).toHaveBeenCalled()
})
})
答案1
得分: 2
建议的方法是不模拟钩子的结果,而是模拟网络响应:
- https://tanstack.com/query/v4/docs/react/guides/testing#testing-network-calls
- https://tkdodo.eu/blog/testing-react-query
英文:
The recommended approach is to not mock the result of the hook, but mock the network response:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论