The course is part of this learning path
This module looks at testing in React. You’ll learn how to set up a test environment, Jest, and other useful tools to test your React App.
The objectives of this module are to provide you with an understanding of:
- How to set up the test environment
- Snapshot testing
- How to test with Props
- How to mock components for testing
- Mock functions
- How to test components asynchronously
- How to test components with routing
- How to test custom hooks
This learning path is aimed at all who wish to learn how to use the ReactJS framework.
We welcome all feedback and suggestions - please contact us at firstname.lastname@example.org to let us know what you think.
If you have started a project using create-react-app, you've already got everything you need to start testing your application set up. It comes with Jest baked into the setup and a sample testbed for the app component. If you examine the package.json file the command test is already in the scripts section on line 15 and you can see that testing library jest-dom, react and user-event have been added as dependencies on line six to eight. This is the package.json file from a new app scaffolded with create-react-app.
The command npm test can be used on the console to run the tests and these will hot-load as you make changes to them or the files they test. We press A to run all of the tests and you can see that the default test provided for the app component passes. Tests should have dot test dot in their filename as a convention to help identify them but create-react-app is configured to look for tests in any file and to use them when running tests.
For this reason, the test files don't need to be saved in the same folder as the item they were testing. In fact, it could get mighty confusing if you don't follow the convention. We've moved the App.test.js file into a folder we've called __testing__. Those underscores help to visually identify it as non-production code folder and is another convention. If you haven't used create-react-app, the React and Jest documentation explain how to add testing to your project.
Introduction to Testing React with Jest - Jest - The What and How of Testing in React - Snapshot Testing - Testing Components with Props - Mocking Components for Testing - Testing State Events Interactions - Mocking Functions - Testing Components Asynchronously - Testing Components with Routing - Testing Custom Hooks