reactjs - 如何使用react-testing-library测试 anchor 的href

标签 reactjs jestjs anchor href react-testing-library

我正在尝试测试我的 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/

相关文章:

javascript - React/Redux 使用选择器选择过滤和排序

javascript - 在现有状态转换期间无法更新(例如在 `render` 内)。渲染方法应该是 props 和 state 的纯函数。在 Index.js 中

html - 当从不同页面引用部分时 CSS 不加载

javascript:;与 javascript:void(0); 比较

javascript - ReactJS 状态更改后内联样式无法正确渲染

javascript - 根据单击该行中的按钮突出显示或删除该行

javascript - 如何在 JEST 中模拟 Cookie.get ('language' )

reactjs - JEST 测试套件无法运行 : TypeError: (0 , _reactRedux.connect) 不是函数

javascript - 在 Jest 测试中将通用数据放在哪里

java - 如何创建一个忽略 href 的 GWT anchor ?