如何解决运行单元测试时出错“你不应该在 <Router> 之外使用 <Link>”
我在这里有一个单元测试,我正在执行一个点击事件。我收到错误:
skiprows = 0 Failed (exception)
skiprows = 1 Failed (exception)
skiprows = 2 Failed (exception)
skiprows = 3 Failed (exception)
skiprows = 4 Failed (exception)
skiprows = 5 Failed (exception)
skiprows = 6 Failed (exception)
skiprows = 7 Failed (exception)
skiprows = 8 Failed (single column)
Subject col1 col2 col3
0 1 10.0 1.0 3.0
1 2 11.0 2.0 4.0
Invariant Failed: You should not use <Link> outside a <Router>
我很确定我知道它为什么哭,但想知道是否有一种简单的方法可以在单元测试时解决这个问题。
我使用的单元测试框架是 describe("when the menu icon has been clicked",() => {
test("the account menu should be displayed",() => {
const { getByTestId } = render(<AccountMenu userDetails={fakeUser}></AccountMenu>);
const button = getByTestId("button-icon-element");
fireEvent.click(button);
screen.debug();
});
});
。
解决方法
您需要在 BrowserRouter 中包装任何正在测试的元素。
const { getByTestId } = render(<BrowserRouter><AccountMenu userDetails={fakeUser}></AccountMenu></BrowserRouter>);
然后就可以点击了。
,您可以创建一个 Wrapper 组件来使用 BrowserRouter
const Wrapper = ({ children }) => {
return (
<BrowserRouter>
{children}
</BrowserRouter>
);
};
const renderWithRouter = (ui) => {
return render(ui,{ wrapper: Wrapper});
};
然后你可以像这样使用它:
const { getByTestId } = renderWithRouter(<AccountMenu userDetails={fakeUser} />)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。