Automated testing is a very important piece in your coding puzzle, In this Article, You will get to setup a testing environment for your React/TypeScript app with @testing-library/react + jest, to get the highest quality code/product! Just a heads, this article doesn’t discuss the “what’s“ of automated testing!
First, Why Automated testing when can just test your app with a mouse and keyboard?
Well, you just have to do it, for your own benefits. And the most extreme example is simulating thousands of virtual users interacting with your web application in order to see how the application behaves. It’s impossible to simulate this kind of behavior by doing manual testing. Features like this save developers a lot of time!
Which packages I need for this setup ?
First, We have to install jest, @types/jest, ts-jest:
yarn:
yarn add --dev jest @types/jest ts-jest
npm:
npm install --save-dev jest @types/jest ts-jest
Assuming you have both react and typescript installed
Now, Let’s setup the environment !
After, installing the packages above, lets init our jest config:
yarn :
yarn ts-jest config:init
npm :
npx ts-jest config:init
you’ll get a jest.config.js:
2. Create test folder and mocks:
Change directory (cd) to your project root, then create test folder inside it create mocks folder:
├── tests
│ ├── components
│ ├── mocks
│ │ ├── fileMock.ts
│ │ └── styleMock.ts
│ ├── pages
│ │ └── login.test.tsx
│ └── setupTests.ts
├── tsconfig.json
├── webpack.config.ts
├── jest.config.ts
└── yarn.lock
Seeing this tree, you’ll have to also create mocks for your models, services, assets .. etc!
fileMock.ts :
styleMock.ts :
also, a setupTests.ts :
3. finalize the config file:
To finish the jest.config file, we have to add couple of more properties :
One more thing, to pair thing with react smoothly, in your .babelrc (babel config file):
{...."presets": [ "@babel/env", ["@babel/preset-react", { "runtime": "automatic" }], "@babel/preset-typescript" ]}
4. Install testing library for react :
Now, you have to add libraries which will allow you to make things happen (access VDOM, interacting …. etc), And those libraries are “@testing-library/dom”, “@testing-library/jest-dom”, “@testing-library/react” and “@testing-library/user-event”
yarn :
yarn add --dev @testing-library/dom @testing-library/jest-dom @testing-library/react @testing-library/user-event
npm :
npm install -D @testing-library/dom @testing-library/jest-dom @testing-library/react @testing-library/user-event
5. Add the jest to package.json :
"scripts": { ... "test": "cross-env NODE_ENV=test jest tests/"}
6. Test your code :
This an example testing the login page:
run the cmd
yarn test
ornpm test
output:
Conclusion:
Hope you got what you came for! if I made any mistake, feel free to report it to me !