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()
})
})
The recommended approach is to not mock the result of the hook, but mock the.network response:
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.