我正在尝试使用 React 测试库对一个简单的导航应用程序进行简单的测试。我目前正在尝试使用RTL's own guide中显示的示例方法,但这似乎不起作用。
应用程序.js
return (
<BrowserRouter>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/hello" component={Hello} />
</div>
</BrowserRouter>
);
主页.jsx
return (
<div data-testid="home-container">
<Link to="/hello">Link to hello</Link>
</div>
);
你好.jsx
return (
<div data-testid="hello-container">
<Link to="/">< Back</Link>
<h1 data-testid="hello-title">Hello component</h1>
</div>
);
在 Home.spec.js 中测试 Home.jsx
test("Navigate to hello page when clicked", async () => {
const history = createMemoryHistory();
render(
<Router history={history}>
<Home />
</Router>
);
// check pre-nav page
expect(screen.getByText(/Link to hello/i)).toBeInTheDocument();
const leftClick = { button: 0 };
userEvent.click(screen.getByText(/Link to hello/i), leftClick);
// check we have navigated to the correct path - THIS PASSES!
expect(history.location.pathname).toBe("/hello");
// check that the content changed to the new page - THIS FAILS!
expect(screen.getByText(/Hello component/i)).toBeInTheDocument();
});
错误...
我似乎得到的错误是它找不到/Hello component/
文本,仍然认为它在Home
组件上......这很奇怪,因为历史位置检查清楚地表明它在Hello
路径上。
Unable to find an element with the text: /Hello component/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, <script />, <style />
<body>
<div>
<div
data-testid="home-container"
>
<a
href="/hello"
>
Link to hello
</a>
</div>
</div>
</body>