我为 react-router 编写了一个非常简单的测试。该测试应该简单地测试带有 to 属性的按钮是否在点击时导航to
一条新路线。
const Routes = () => {
return (
<Switch>
<Route
exact
path="/"
render={() => (
<CornerButton to="/route">{btnText}</CornerButton>
)}
/>
<Route exact path="/route" render={() => <div>Route</div>} />
</Switch>
);
};
it("renders a route change with 'to' prop", async () => {
render(
<div>
<MemoryRouter initialEntries={["/"]}>
<Routes />
</MemoryRouter>
</div>
);
const btn = screen.getByRole("button", { name: btnText });
fireEvent.click(btn);
const newRoute = screen.getByText(/Route/i);
expect(newRoute).toBeInTheDocument();
});
我看到了错误:
<块引用>TestingLibraryElementError: Unable to find an element with the text: /路线/i。
按钮工作正常,呈现的 HTML 看起来不错:
<body>
<div>
<div>
<a
class="sc-jgHCyG begwzL"
href="/route"
style="text-decoration: none;"
>
<button
class="sc-bBrOnJ gZtvsD"
color="primary"
type="button"
>
<div
class="sc-cOajty wNAWC"
>
<div
class="sc-khAkjo jvrrvJ"
>
text
</div>
<div
class="sc-AzgDb fmENQv"
/>
</div>
</button>
</a>
</div>
</div>
</body>
我希望得到一些帮助。
编辑:
我更接近解决方案,但这种行为对我来说似乎很奇怪。
如果我使用:const btn = screen.getByRole("link", { name: btnText });
代替:const btn = screen.getByRole("button", { name: btnText });
一切正常。这是否与按钮的默认行为有关?我不在组件内部调用 preventDefault()
。但同样,我在测试之外点击按钮没有问题。
答案 0 :(得分:1)
当我尝试这段代码时,测试通过了:
new_idx = pd.DatetimeIndex([datetime.combine(date,time) for date,time in new_idx.values])
因此,您的 import { Switch, Route, MemoryRouter, Link } from "react-router-dom";
import { render, screen, fireEvent } from "@testing-library/react";
const Routes = () => {
return (
<Switch>
<Route
exact
path="/"
render={() => (
<div>
<div>
<Link to="/route">
<button color="primary" type="button">
<div>
<div>btnText</div>
<div />
</div>
</button>
</Link>
</div>
</div>
)}
/>
<Route exact path="/route" render={() => <div>Route</div>} />
</Switch>
);
};
it("renders a route change with 'to' prop", async () => {
render(
<div>
<MemoryRouter initialEntries={["/"]}>
<Routes />
</MemoryRouter>
</div>
);
const btn = screen.getByRole("button", { name: "btnText" });
fireEvent.click(btn);
const newRoute = screen.getByText(/Route/i);
expect(newRoute).toBeInTheDocument();
});
中可能还有其他原因导致按钮在测试中无法正常工作。