[英]How to test link using react-testing-library and jest
Trying to learn testing.努力学习测试。 Using testing-library, Jest, and React-Router v6, and Typescript.
使用测试库、Jest 和 React-Router v6 和 Typescript。 I'm trying to figure out how to test a link.
我试图弄清楚如何测试链接。 I've been looking all over the place for a solution and I can't find one.
我一直在到处寻找解决方案,但找不到。 Using React-Router v6.
使用 React-Router v6。 Code looks like the following (link is just a regular element with an href) just want to make sure the user gets to the new page (in this case the login page from the forgot password page).
代码如下所示(链接只是一个带有 href 的常规元素)只是想确保用户进入新页面(在这种情况下是来自忘记密码页面的登录页面)。
//omitted imports but imported all appropriate items from below
describe('ForgotPassword', () => {
test('User can navigate to login screen', async () => {
render(
<MemoryRouter initialEntries={['/forgot-password' ]}>
<ForgotPassword />
</MemoryRouter>)
userEvent.click(screen.getByRole('link', { name: 'Back to Login' }))
await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Login' })).toBeInTheDocument()
})
})
//also tried:
describe('ForgotPassword', () => {
test('User can navigate to login screen', async () => {
render(
<MemoryRouter initialEntries={['/forgot-password' ]}>
<Routes>
<Route path='/forgot-password' component={<ForgotPassword />} />
<Route path='/login' component={<Login />} />
<Routes>
</MemoryRouter>)
userEvent.click(screen.getByRole('link', { name: 'Back to Login' }))
await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Login' })).toBeInTheDocument()
})
})
//also tried the following:
const history = createMemoryHistory({ initialEntries: ['/home'] });
const { getByText } = render(
<Router history={history}>
<ButtonLogin />
</Router>
);
got a TS error: Property 'history' does not exist on type 'IntrinsicAttributes & RouterProps'.
//also tried using fireEvent instead of userEvent
Your second try was nearly good.你的第二次尝试几乎是好的。 You'd have to change
component
prop to element
in react-router v6.x:您必须在 react-router v6.x 中将
component
属性更改为element
:
describe('ForgotPassword', () => {
test('User can navigate to login screen', async () => {
function ForgotPassword() {
return (
<div>
<h1>Home</h1>
<Link to="../login">Back to Login</Link>
</div>
);
}
render(
<MemoryRouter initialEntries={['/forgot-password' ]}>
<Routes>
<Route path='/forgot-password' element={<ForgotPassword/>} />
<Route path='/login' element={<h1>Login</h1>} />
<Routes>
</MemoryRouter>)
userEvent.click(screen.getByRole('link', { name: 'Back to Login' }))
await waitFor(() => {
expect(screen.getByRole('heading', { name: 'Login' })).toBeInTheDocument()
})
})
})
Note: whenever in doubt, React-router-dom 's internal tests are a great way to have a hint.注意:如有疑问, React-router-dom的内部测试是获得提示的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.