2

I'm developing my React app & when I tried to do some unit tests using react testing library. I'm not able to run my tests successfully.

Does anyone know if this is related to the V6 React upgrade?

here is my example test code that i'm trying to run:

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders a button to enter', () => {
  render(<App />);
  const linkElement = screen.getByText(/Play/i);
  expect(linkElement).toBeInTheDocument();
});

App.js

function App() {
  return (
    <div className="App">
      <Routes>
        <Route exact path="/" element={<LandingPage />} />
        <Route exact path="/home" element={<Home />} />
        <Route exact path="/videogame/:id" element={<Detail />} />
        <Route exact path="/creategame" element={<CreateGame />} />
      </Routes>
    </div>
  );
}

export default App;

LandingPage

const LandingPage = () => {
  return (
    <div className="landing">
      <Link to="/home">
        <button className="landingBtn">Play</button>
      </Link>
    </div>
  );
};

export default LandingPage;

Thanks!

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • 1
    _"i'm not able to run my tests successfully"_ - can you be more specific? What's not working as expected? Also, please provide the code for the component under test. – juliomalves Dec 05 '21 at 18:51
  • the error is: Test Suites: 0 of 1 total ● renders a button to enter useRoutes() may be used only in the context of a component. – Natalia Favala Dec 06 '21 at 11:41

1 Answers1

0

Since you're testing App component and it consist of routes you cannot select /Play/i text element here instead import the exact component to test.

react-testing-library with react router

For testing router files

Mock Router to be a div and contains its children code. This works the following way: You need the folder __mocks__/react-router-dom.js which contains the following code:

import React from 'react';

const reactRouterDom = require("react-router-dom")
reactRouterDom.BrowserRouter = ({children}) => <div>{children}</div>
module.exports = reactRouterDom

Now you can use the MemoryRouter to define the path to which the Route should point to.

App.test.js:

import React from "react";
import { render } from "@testing-library/react";
import { MemoryRouter } from 'react-router-dom';
import App from './App';

describe("unit-test", () => {
    it("renders the right component with following path '/home'", () => {
        const { getByTestId } = render(
            <MemoryRouter initialEntries={['/home']}>
                <App></App>
            </MemoryRouter>
        )

        let HomeComponent= getByTestId("home-component")

        expect(HomeComponent).toBeInTheDocument()
    })
})

Hithesh kumar
  • 1,008
  • 9
  • 25