[英]How to test anchor's href with react-testing-library
I am trying to test my anchor tag.我正在尝试测试我的锚标记。 Once I click it, I want to see if the
window.location.href
is what I expect.单击它后,我想查看
window.location.href
是否符合我的预期。
I've tried to render the anchor, click it, and then test window.location.href
:我尝试渲染锚点,单击它,然后测试
window.location.href
:
test('should navigate to ... when link is clicked', () => {
const { getByText } = render(<a href="https://test.com">Click Me</a>);
const link = getByText('Click Me');
fireEvent.click(link);
expect(window.location.href).toBe("https://www.test.com/");
});
I am expecting the test to pass, but instead the window.location.href is just "http://localhost/"
meaning it is not getting updated for whatever reason.我希望测试能够通过,但 window.location.href 只是
"http://localhost/"
,这意味着无论出于何种原因它都没有得到更新。 I even tried wrapping my expect with await wait
, but that didn't work either.我什至尝试用
await wait
包装我的期望,但这也不起作用。 I can't find much information about testing anchors with react-testing-library
.我找不到太多关于使用
react-testing-library
测试锚点的信息。 Maybe there is even a better way to test them than what I am doing.也许有比我正在做的更好的方法来测试它们。 🤷♂️
🤷♂️
Jest uses jsdom to run its test. Jest 使用 jsdom 来运行它的测试。 jsdom is simulating a browser but it has some limitations.
jsdom 是模拟浏览器,但它有一些限制。 One of these limitations is the fact that you can't change the location.
这些限制之一是您无法更改位置。 If you want to test that your link works I suggest to check the
href
attribute of your <a>
:如果您想测试您的链接是否有效,我建议您检查
<a>
的href
属性:
expect(screen.getByText('Click Me').closest('a')).toHaveAttribute('href', 'https://www.test.com/')
I found a solution that may help others.我找到了一个可以帮助其他人的解决方案。 The
<a>
element is considered a link
role by React Testing Library. <a>
元素被 React 测试库视为link
角色。 This should work:这应该有效:
expect(screen.getByRole('link')).toHaveAttribute('href', 'https://www.test.com');
If you are using screen
which should be the preferred way, by RTL authors:如果您使用的
screen
应该是首选方式,RTL 作者:
const linkEl = screen.getByRole('link', { name: 'Click Me' });
expect(linkEl).toHaveAttribute('href', '...')
Similar, without screen (name can be string or RegExp):类似,没有屏幕(名称可以是字符串或正则表达式):
const linkEl = getByRole('link', { name: 'Click Me' });
您可以简单地使用它来代替:
expect(getByText("Click Me").href).toBe("https://www.test.com/")
simple and easy.简单易行。
try this尝试这个
it('should be a link that have href value to "/login"', () => {
render(<SigningInLink />);
const link = screen.getByRole('link', { name: /log in/i });
expect(link.getAttribute('href')).toBe('/login');
});
Maybe its overtly engineered in this case.也许它在这种情况下被公然设计。 But you can also use data-testid attribute.
但您也可以使用 data-testid 属性。 This guarantees that you are getting the a tag.
这可以保证您获得 a 标签。 I think there are benefit to this for more complex components.
我认为这对更复杂的组件有好处。
test('should navigate to ... when link is clicked', () => {
const { getByTestId } = render(<a data-testid='link' href="https://test.com">Click Me</a>);
expect(getByTestId('link')).toHaveAttribute('href', 'https://test.com');
});
You may have several links to check on a page.您可能需要在一个页面上查看多个链接。 I found these suggestions very useful.
我发现这些建议非常有用。 What I did to adapt it to checking 5 links on the same page -
我做了什么来调整它以检查同一页面上的 5 个链接 -
screen()
method best practice - it is more reliablescreen()
方法查询页面上的链接最佳实践——更可靠toHaveAttribute
method rather than navigating with the window object - In react with the virtual DOM, if you try and navigate to another page the link directs to http://localhost/link rather than testing the redirecttoHaveAttribute
方法而不是使用窗口对象导航 - 与虚拟 DOM 做出反应,如果您尝试导航到另一个页面,则链接指向 http://localhost/link 而不是测试重定向test('should navigate to url1 when link is clicked', () => {
const componentName = render(<Component/>)
const url1 = getByText("https://www.test.com/")
expect(ur1).toBeInTheDocument()
screen.userEvent.click(url1);
expect(url1).toHaveAttribute('href', 'https://www.test.com/')
});
This is what I use:这就是我使用的:
const linkToTest = screen.getByRole("link", { name: /link to test/i })
// I used regex here as a value of name property which ignores casing
expect(linkToTest.getAttribute("href")).toMatchInlineSnapshot();
and then run the test, brackets of toMatchInlineSnapshot
will be filled with the value that's there in your code.然后运行测试,
toMatchInlineSnapshot
的括号将填充您代码中的值。
This has the advantage of not hard coding it, and maintaining this will be easier.这样做的好处是不会对其进行硬编码,并且维护起来会更容易。
For eg: it will be filled like this:例如:它将像这样填充:
expect(linkToTest.getAttribute("href")).toMatchInlineSnapshot(`"link/to/somewhere"`);
and next time, suppose you change this link to something else in your codebase, the runner will ask you if you want to update, press u
and it will be updated.下一次,假设您将此链接更改为代码库中的其他内容,跑步者会询问您是否要更新,按
u
它将被更新。 (Note, that you need to check that this update is correct). (注意,您需要检查此更新是否正确)。
Know more about inline snapshots on Jest Docs在Jest Docs上了解有关内联快照的更多信息
I am trying to test my anchor tag.我正在尝试测试我的锚标签。 Once I click it, I want to see if the
window.location.href
is what I expect.单击它后,我想查看
window.location.href
是否符合我的预期。
I've tried to render the anchor, click it, and then test window.location.href
:我尝试渲染锚点,单击它,然后测试
window.location.href
:
test('should navigate to ... when link is clicked', () => {
const { getByText } = render(<a href="https://test.com">Click Me</a>);
const link = getByText('Click Me');
fireEvent.click(link);
expect(window.location.href).toBe("https://www.test.com/");
});
I am expecting the test to pass, but instead the window.location.href is just "http://localhost/"
meaning it is not getting updated for whatever reason.我期待测试通过,但 window.location.href 只是
"http://localhost/"
这意味着它没有因任何原因得到更新。 I even tried wrapping my expect with await wait
, but that didn't work either.我什至尝试用
await wait
包装我的期望,但这也不起作用。 I can't find much information about testing anchors with react-testing-library
.我找不到关于使用
react-testing-library
测试锚点的很多信息。 Maybe there is even a better way to test them than what I am doing.也许有比我正在做的更好的方法来测试它们。 🤷♂️
🤷♂️
这对我有用:
expect(screen.getByText('Click Me').closest('a')?.href).toEqual('https://test.com');
Here is what I did, works for me using testing-library/react这是我所做的,使用测试库/反应对我有用
import { render, screen } from '@testing-library/react';
import {HomeFeature} from '../Components/HomeFeature.tsx';
let imp_content = [
{
title: "Next.js",
link: "https://nextjs.org/",
},
{
title: "React",
link: "https://reactjs.org/",
},
{
title: "Firebase",
link: "https://firebase.google.com/",
},
{
title: "Tailwind",
link: "https://tailwindcss.com/",
},
{
title: "TypeScript",
link: "https://www.typescriptlang.org/",
},
{
title: "Jest.js",
link: "https://jestjs.io/",
},
{
title: "testing-library/react",
link: "https://testing-library.com/",
}
];
imp_content.map((content) => {
test(`${content.title} contains ${content.link}`, () => {
render(<HomeFeature />);
expect(screen.getByText(content.title).closest('a')).toHaveAttribute('href', content.link);
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.