【发布时间】:2021-03-13 05:46:57
【问题描述】:
我在 React 中遇到了一个需要挂钩两次的测试场景。在这种情况下,我在同一页面上的两种情况下使用了一个名为 useGet() 的钩子。在我尝试的所有时间中,只有最后一个结果被嘲笑,而第一个结果未定义。有谁知道在同一个测试中模拟两者的方法,以便我可以在测试中呈现完整的 html?
屏幕上使用的需要模拟的变量示例:
const getBoletoCashIn = useGet('all-boletos-cash-in')
const getBoletoCashOut = useGet('all-boletos-cash-out')
try {
const getCashIn = await getBoletoCashIn.refetch()
const getCashOut = await getBoletoCashOut.refetch()
console.log(getCashIn, getCashOut)
} catch(error) {
console.log(error)
}
测试尝试:
const mockGetData = jest.fn()
jest.mock('@/hooks/useRest', () => {
return {
useGet: () => {
return {
refetch: mockGetData
}
}
}
})
const customRender = (ui: JSX.Element, { providerProps, ...renderOptions }: { providerProps: { url: { baseUrl: string } } }) => {
return render(
<GlobalProvider>
<GlobalStyles />
{ui}
</GlobalProvider>,
renderOptions
)
}
describe('Cash-In & Cash-Out chart component', () => {
it('', async () => {
const { debug } = customRender(
<CashInCashOutChart />,
{ providerProps }
)
// Array aleatório
mockGetData.mockImplementationOnce(() => ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
mockGetData.mockImplementationOnce(() => ([1, 2, 3, 4, 5]))
await waitFor(() => expect(mockGetData).toHaveBeenCalledTimes(1))
await waitFor(() => {
debug()
})
})
})
【问题讨论】:
标签: javascript reactjs jestjs mocking render