How to test react applications ? Jest & React Testing Library (alternative to enzyme)
How to setup test for our app ?
Why test cases ?
- New code should not old code
- Not breaking existing code - Maintainability
TDD - test Driven Development ? Test cases even before writing code, development becomes very slow.
Types of tesing :
-
Manual testing -> human testing the code
-
Automated testing -> code testing the code Eg: Selenium
-
E2E tetsing -> test the whole flow by stimulating . Eg:cypress This is offloaded to QA team. Headless browser -> browser does not have to do teh work of laoding UI in browser. It makes testing faster.
-
Unit testing -> core job of developers -> testing small unit of code
-
Integration testing -> Data flow between components
-
Performance, Regression and Smoke testing
React-Testing-library
-
Install React Testing library - npm install --save-dev @testing-library/react @testing-library/jest-dom
-
Install Jest - npm install -D jest
-
Configure Jest -> npx jest --init
-
Typescript -> N
-
environment -> jsdom (broswer-like)
-
code coverage -> y
-
provider for coverage -> babel
-
automatically clear before test -> y
-
Creates jest.config.js
-
scripts -> test : jest
-
npm install -D jest-environment-jsdom
-
jest is trying to find test cases in the app under tests folder
-
Create first test -> sum.test.js under tests folder
-
test("testcase name ", () => { })
-
Every test case should have some assertion -
expect
to return -toBe
expeect(sum(2,3)).toBe(5) -
import sum.js (component) inside sum.test.js
-
npm install --save-dev babel-jest @babel/core @babel/preset-env - why ? because jest does not understand import statement.
-
to configure babel -> babelrc file or babel.config.js
-
package.json ->in scripts watch test : "test --watch"