反应 - 测试 - 你不应该<Link>在外面<Router>使用


Invariant failed: You should not use <Link> outside a <Router>

在尝试用为组件编写测试时得到这一点

test("renders post list div ", () => {
const posts = [ {
created: '-',
title: '-',
slug : '-',
content : '-',
author : '-' } ];
const div = document.createElement('div');
ReactDOM.render(<PostList posts = {posts} />, div);
expect(div.querySelector("div")).toBeTruthy();
});

我在主应用中调用的Post中使用<Link ...

应用程序本身使用路由器如下:

return (
<ThemeContext.Provider value={theme} >
<Router>
<div className="App" style={{ paddingLeft: "10px" }}>
<Header text='Welcome' />
<PostMessage type={postMessage} setPostMessage={setPostMessage} />
<ChangeTheme theme={theme} setTheme={setTheme} />
<UserBar
username={username} setUsername={setUsername}
loggedIn={loggedIn}
onLogin={handleLogin} />
<br />
<hr />
<Switch>
<Route exact path='/'
...
{loggedIn && <PostList posts={posts} /> }
...

所以我在路由器树中。如何让测试也能做到这一点?

RouterRoute中封装元素有效:

...
import { BrowserRouter as Router, Route } from 'react-router-dom';
...

test("renders post list div ", () => {
const posts = [ {
created: '-',
title: '-',
slug : '-',
content : '-',
author : '-' } ];
const div = document.createElement("div" );
div.setAttribute('id', 'root' );
ReactDOM.render
(<Router><Route path='/'><PostList posts = {posts} /></Route></Router>, div);
expect(div.querySelectorAll("div.post")[0].innerHTML).toContain('Written by <b>-</b>');
});

相关内容

  • 没有找到相关文章

最新更新