Cool and simple examples using jest to test a node API. The first version of this repo was based on this post.
- what's the project structure?
- how to run and test the endpoint
- how to test the code
- how to generate the coverage report
- about the sonarcloud integration
- licensing
.
├── LICENSE
├── README.md
├── package.json
├── package-lock.json
├── src
│ ├── controller.js
│ ├── index.js
│ ├── router.js
│ └── service.js
└── test
├── controller.test.js
├── index.test.js
├── router.test.js
└── service.test.js
Prerequisites
$ node --version
v16.6.2
Run
$ npm start
Test the endpoint
$ curl localhost:3000/posts
We're using Jest, you can run this npm script:
$ npm test
PASS test/index.test.js
PASS test/router.test.js
PASS test/controller.test.js
PASS test/service.test.js
Test Suites: 4 passed, 4 total
Tests: 7 passed, 7 total
Snapshots: 0 total
Time: 2.269 s
We're using istanbul and it's included with Jest, you can run this npm script:
$ npm run coverage
PASS test/index.test.js
PASS test/router.test.js
PASS test/controller.test.js
PASS test/service.test.js
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 95.83 | 100 | 85.71 | 95.83 |
controller.js | 100 | 100 | 100 | 100 |
index.js | 83.33 | 100 | 0 | 83.33 | 9
router.js | 100 | 100 | 100 | 100 |
service.js | 100 | 100 | 100 | 100 |
---------------|---------|----------|---------|---------|-------------------
Test Suites: 4 passed, 4 total
Tests: 7 passed, 7 total
Snapshots: 0 total
Time: 1.459 s
Also you can check the results in the generated coverage\lcov-report\index.html
file
This repo is linked to a project in sonarcloud and that services it's free only if your source code is written with non commercial goals. You can check this document and this GitHub Action information if you want to know more about the integration.
We're using Git Hooks scripts using husky, what a nice tool!
So, anytime you'll make a commit you'll see something like that
$ git commit -am 'feat: add basic husky support'
> jest test/**.test.js
PASS test/index.test.js
PASS test/service.test.js
PASS test/router.test.js
PASS test/controller.test.js
Test Suites: 4 passed, 4 total
Tests: 7 passed, 7 total
Snapshots: 0 total
Time: 1.812 s
Ran all test suites matching /test\/controller.test.js|test\/index.test.js|test\/router.test.js|test\/service.test.js/i.
[master 508a8eb] feat: add basic husky support
4 files changed, 16 insertions(+), 3 deletions(-)
create mode 100644 .husky/.gitignore
create mode 100755 .husky/pre-commit