使用 React 测试库提交后测试重定向 [英] Testing redirect after submit with React Testing Library
本文介绍了使用 React 测试库提交后测试重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试测试登录组件.具体来说,它会在成功登录时重定向.手动测试时它工作正常.但在我的测试中,它从不进行重定向,因此找不到注销"链接:
I'm trying to test a login component. Specifically that it redirects on a successful login. It works fine when testing it manually. But in my test it never does the redirect and it can therefor not find the "Logout" link:
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 进行重定向,如下所示:
I'm redirecting with react-router
version 4, like so:
{state.resolved ? <Redirect to="/" /> : null}
我是不是用错了方法?
推荐答案
你可以模拟 Redirect
组件的实现来显示一些包含路径的文本,而不是重定向到它:
You can mock the Redirect
component's implementation to show some text including the path instead of redirecting to it:
jest.mock('react-router-dom', () => {
return {
Redirect: jest.fn(({ to }) => `Redirected to ${to}`),
};
});
并期望您的组件显示具有正确路径的文本:
and expect your component to display the text with the correct path:
expect(screen.getByText('Redirected to /')).toBeInTheDocument();
这篇关于使用 React 测试库提交后测试重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文