我正在尝试测试我的 anchor 标记。单击它后,我想查看 window.location.href
是否是我所期望的。
我尝试渲染 anchor ,单击它,然后测试 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/");
});
我希望测试能够通过,但 window.location.href 只是 "http://localhost/"
,这意味着无论出于何种原因它都没有得到更新。我什至尝试用 await wait
包装我的期望,但这也不起作用。我找不到太多有关使用 react-testing-library
测试 anchor 的信息。也许有比我正在做的更好的方法来测试它们。 🤷♂️
最佳答案
Jest 使用 jsdom 来运行其测试。 jsdom 是模拟浏览器,但它有一些限制。这些限制之一是您无法更改位置。如果您想测试您的链接是否有效,我建议检查 href
您的<a>
的属性:
expect(screen.getByText('Click Me').closest('a')).toHaveAttribute('href', 'https://www.test.com/')
更新
现在最好使用getByRole
如果可能的话:
expect(screen.getByRole('link', { name: 'Click Me' })).toHaveAttribute('href', 'https://www.test.com/')
关于reactjs - 如何使用react-testing-library测试 anchor 的href,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57827126/