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

Getting this in trying to write a test for a component with

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();
});

I use <Link ... inside of a Post which gets called within the main app

App itself uses Router like this:

  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} /> }
              ...

So I am within a Router tree. How to get the test to be able to do this also?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • Does this answer your question? [You should not use outside a ](https://stackoverflow.com/questions/48640280/you-should-not-use-link-outside-a-router) – jonrsharpe Jul 11 '20 at 09:26
  • 3
    But `PostList` isn't being rendered in the APP tree when it's being tested in isolation, it's simply rendered into that `div`. You'll need to wrap it in a Router in the test. – Drew Reese Jul 11 '20 at 09:27

1 Answers1

1

Wrapping the element in Router and Route worked:

...
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>');
});
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497