Here ‘expect’ is an assertion library, used to check the correctness.
Why should I choose Jest?
- Jest is already bundled with JSDOM to enable DOM testing.
- It supports running tests in parallel; so it is faster.
- It supports Promise too.
- It easily tests React apps.
- It provides out of the box code coverage.
- It is backed by Facebook.
1. Get some sample ReactJS application or clone https://github.com/haggarwal90/product-catalog-reactjs.git
2. Go to the project and execute the following command
→ Yarn add jest babel-jest enzyme enzyme-adapter-react-15
3. Define Jest configuration, create jest.config.js at the root and add the below code-
Note: Jest’s configuration can be defined in the package.json file of your project, or through a jest.config.js file or through the –config <path/to/js|json> option.
4. Create test directory at the root. Inside test folder create jest.setup.js and add the following code-
5. Add script to package.json
Let’s begin writing our first test suite
1. Go to component folder and create a test file for any component.
Example for product.jsx -> product.test.jsx and add below test-
2. Run npm run test and you will see the test pass successfully.
3. Similarly, you can add more test cases like “Component with correct default state” and “event/action simulation”
We have learned about Jest, the importance of Jest, Jest environment setup & configurations and wrote some basic test cases. We’ll do more like snapshot testing, mocking data/services, code coverage, etc in upcoming blogs.
Jest official documentation.