0

Im new at react-testing-library!

I'm getting this error when I test the Navbar component

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

my Navbar component :

function Navbar() {
  return (
    <Nav>
      <Logo>
        <h3>
          <LogoLink to="">conduit</LogoLink>
        </h3>
      </Logo>
      <NavList>
        <Li>
          <NavLink to="">Home</NavLink>
        </Li>
        <Li>
          <NavLink to="signin">Sign in</NavLink>
        </Li>
        <Li>
          <NavLink to="signup">Sign up</NavLink>
        </Li>
      </NavList>
    </Nav>
  );
}

export default Navbar;
  • my test:

     import { render } from '@testing-library/react';
      import React from 'react';
      import Navbar from './Navbar';
    
      it('should render the Navbar component', () => {
        const mockNavbar = jest.fn();
        const { debug } = render(<Navbar navbar={mockNavbar} />);
        debug();
      });
    

I'm also using styled- component, my styled component:

const LogoLink = styled(Link)`
  color: #5cb85c;
  text-decoration: none;
  &:hover {
    cursor: pointer;
  }
`;

const NavLink = styled(Link)`
  text-decoration: none;
  color: #aba6a6;
  &:hover {
    cursor: pointer;
    color: #2e2c2c;
  }
`;
Alaa Khalila
  • 139
  • 9
  • 1
    From the [docs](https://reactrouter.com/web/guides/testing): *"If you try to unit test one of your components that renders a `` or a ``... , we recommend you wrap your unit test in one of the Router components: the base `Router` with a history prop, or a ``, ``, or `` (if window.history is available as a global in the test enviroment)."* – Janez Kuhar Feb 26 '21 at 18:52
  • ohhh ty worked! @JanezKuhar – Alaa Khalila Feb 26 '21 at 18:58

2 Answers2

1

Your <App> probably not wrapped by Router so you should wrap your app between <Router>. In this case I'm referencing App as your first component when you create create-react-app because I do not know your code structure.

Evren
  • 974
  • 1
  • 3
  • 9
1
function App() {
  return (
    <Router>
      <GlobalStyle />
      <Header />
      <Switch>
        <Route path="/signup" component={Signup} />
        <Route path="/signin" component={Signin} />
        <Route exact path="/" component={Content} />
      </Switch>
    </Router>
  );
}

export default App;
Alaa Khalila
  • 139
  • 9