我正在尝试测试登录组件。具体来说,它会在成功登录后重定向。手动测试时效果很好。但是在我的测试中,它从不执行重定向,因此无法找到“注销”链接:
test('successfully logs the in the user', async () => {
const fakeUserResponse = {success: true, token: 'fake_user_token'}
jest.spyOn(window, 'fetch').mockImplementationOnce(() => {
return Promise.resolve({
json: () => Promise.resolve(fakeUserResponse),
})
})
const { getByText, getByLabelText, findByTestId } = render(<Router><Login /></Router>)
fireEvent.change(getByLabelText(/email/i), {target: {value: 'dan@example.com'}})
fireEvent.change(getByLabelText(/password/i), {target: {value: 'password1234'}})
fireEvent.click(getByText(/submit/i))
await waitForElement(() => getByText(/logout/i));
})
我正在使用react-router
版本4进行重定向,如下所示:
{state.resolved ? <Redirect to="/" /> : null}
我会以错误的方式处理吗?
答案 0 :(得分:0)
所以我最终这样做了:
const { getByText, getByLabelText, } = render(
<Router>
<Login/>
<Switch>
<Route path="/">
<div>logged out</div>
</Route>
</Switch>
</Router>
)
fireEvent.change(getByLabelText(/email/i), {target: {value: 'dan@example.com'}})
fireEvent.change(getByLabelText(/password/i), {target: {value: 'password1234'}})
fireEvent.click(getByText(/submit/i))
await waitForElement(() => getByText(/logged out/i))
答案 1 :(得分:0)
您可以模拟Redirect
组件的实现,以显示一些包含路径的文本,而不是重定向至该路径:
jest.mock('react-router-dom', () => {
return {
Redirect: jest.fn(({ to }) => `Redirected to ${to}`),
};
});
,并希望您的组件以正确的路径显示文本:
expect(screen.getByText('Redirected to /')).toBeInTheDocument();