Before we start the config we need to now some things:
Why test my app? 🤔
To make your service scalable, and more consistent!
What is jest? 💭
Because is the most complete and easy to use!
First of all you need to installing the packages below on your project:
- Jest the test framework:
yarn add jest -D
- jest types is a inteliscense to use jest:
yarn add @types/jest -D
- Supertest is a framework to simulate http requisitions:
yarn add supertest -D
Now we need to make initial jest config.
To do that we execute the command below:
yarn jest --init
After that the console make some questions to you, you need to answer like the image below:
Now you will find a file called "jest.config.js" on your root project.
The next step is ajust this config file like below:
- Bail is the option we set to define the number of errors that make the tests break, in this case i always like to set one:
bail: 1,
- Clearmocks is the option that clear mocks after tests, this option we set true:
clearMocks: true,
- collectCoverage this option enable or disable the coe coverage, i like to set as true:
collectCoverage: true,
- collectCoverageFrom this option define the path or file s to collect the coverage, usually i set the path where stay my business logic:
collectCoverageFrom: [
'src/app/Controllers/*.js',
],
- coverageDirectory is the place where jest can put the coverage result, i usualy put coverage inside the test folder:
coverageDirectory: '__tests__/coverage',
- coverageReporters this option set the type of reporters for coverage result, i like to user reports below:
coverageReporters: ['text', 'lcov', 'json'],
- testMatch this option set the test files extensions:
testMatch: ['**/__tests__/**/*.test.js'],
Now we can create the folder structure as the image below:
And that is it, now you reandy to starting test your api with jest!
Top comments (0)