2

I'm writing test code for my react app. I want to write test code that tests screen transition from Page A to Page B.

However, somehow the event to make user move to Page B from Page A doesn't work in my test code.

This is the test code.

  • Test code
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { StaticRouter } from 'react-router-dom';
import Routes from '../src/rouer';

const App = () => {
  return (
    <StaticRouter>
      <Routes />
    </StaticRouter>
  );
};

describe('Test screen transition', () => {
  it('Test screen transition', () => {
    render(<App />);
    screen.debug();

    // I want this line makes the click event fired, but it doesn't
    fireEvent.click(screen.getByText('Go to Page B from Page A'));
    screen.debug();
  });
});
  • This is my Page A component
import * as React from 'react';
import { Link } from 'react-router-dom';

const A = () => {
  return (
    <>
      <div>
        <Link to="/b">Go to Page B from Page A</Link>
      </div>
    </>
  );
};

export default A;
  • This is my Page B component
import * as React from 'react';
import { Link } from 'react-router-dom';

const B = () => {
  return (
    <>
      <div>
        This is Page B
      </div>
    </>
  );
};

export default B;
Satoru Kikuchi
  • 1,069
  • 2
  • 21
  • 33
  • 2
    Something to consider: end-to-end tests (using a tool such a Cypress) might be better for this sort of thing, and empower even better tests to be created :) – Caleb Miller Jan 07 '21 at 05:52
  • Seems more like integration testing that unit testing. You generally don't test 3rd party code in a unit test. Assume in isolation of "A" that the `Link` component you didn't write works and is properly tested. – Drew Reese Jan 07 '21 at 06:20
  • 1
    If you want to test navigation you need access to the history, see e.g. the test I wrote [here](https://github.com/textbook/starter-kit/blob/master/client/src/pages/Home.test.js). You can see examples at https://testing-library.com/docs/example-react-router/, https://reactrouter.com/web/guides/testing. Related question: https://stackoverflow.com/q/65270992/3001761. – jonrsharpe Jan 07 '21 at 09:31

0 Answers0