React Testing Techniques

This project implements an online shopping application to show techniques used
to test React applications. We use the following tools for testing:

Unit Testing

  • Jest – a testing framework designed to ensure
    correctness of any JavaScript or TypeScript codebase

  • React Testing Library – a testing framework
    for React components that encourages better testing practices

  • Mock Service Worker – a framework to mock APIs by
    intercepting requests at the network level. It allows us to reuse the same
    mock definition for testing, development, and debugging.

Integration Testing

  • Cypress – a testing framework for fully built Web
    applications running in a browser

Manual Testing

  • Storybook – a tool that helps build components in
    isolation and record their states as stories. Stories make it easy to explore
    a component in all its permutations no matter how complex. They also serve as
    excellent visual test cases. Storybook testing can also be automated. For
    details, look at the
    Storybook documentation.

This project was bootstrapped with
React Accelerate.

Testing Topics

  • Structuring code for easier testing – pure JavaScript logic vs. React components
  • Snapshot testing vs. traditional unit testing
  • Suppressing console errors
  • Checking for existence of an element
  • Waiting for removal of an element
  • Waiting for something to happen
  • User events (note how {selectall} works)
  • Mocking a callback (see ProductView test)
  • Use MSW instead of excessive mocking
  • Overriding MSW handlers (see CartView test)
  • Mocking MSW handlers (see CatalogView test)
  • Difference between queryBy, getBy and findBy
  • Testing for page navigation

Getting Started

Note: If you prefer to use npm, please feel free to replace the yarn commands
in this section with equivalent npm commands.

Make sure your development machine is set up for building React apps. See the
recommended setup procedure
here.

Execute the following commands to install dependencies:

yarn install

Execute the following commands to run the app:

yarn start

Now point your browser to http://localhost:3000/.

Running Unit Tests

Execute one of the following command to run unit tests.

yarn test # interactive mode

# OR

yarn test:coverage # non-interactive mode with coverage information

Running End-to-End Tests

yarn start # starts a local server hosting your react app

# in a difference shell, run cypress
yarn cypress:open

Running Storybook

yarn storybook

Screenshots

Home page with item catalog and shopping cart

Home Page

GitHub

https://github.com/nareshbhatia/react-testing-techniques