Jest runs automated tests for JavaScript code. Use it to test a library or an individual microservice before relying on broader application tests. It needs little configuration and can rerun tests as code changes. section 9.5 section 9.5.1 section 10.3
Set up Jest in a Node.js project:
- Install it with `npm install --save-dev jest`. The development dependency is not needed in production. section 9.5.2
- Generate a configuration file with `npx jest --init`. By default, Jest finds a test named `math.test.js` for code in `math.js`. section 9.5.2 section 9.10
Listing 9.1 Configuration file for Jest
module.exports = {
clearMocks: true, #1
testEnvironment: "node", #2
};
A small configuration enables `clearMocks` and selects the `node` test environment. section 9.5.2
From a library to a microservice
For a math library, put tests in `math.test.js`: Jest loads that file, which invokes code in `math.js` and checks the result. For a microservice unit test, Jest loads `index.test.js`, which loads the service code. Mock Express and MongoDB so the test does not start a real HTTP server or connect to a database. Tests can then check that the service starts and that its `/videos` route retrieves records. section 9.5 section 9.6 section 9.6.4
Run tests with `npx jest`, or use `npm test` when the project has a test script. Use `npx jest --watch` to rerun tests as code changes; `--watchAll` watches all files rather than only those Git reports as changed. In the metadata microservice, `npm run test:watch` provides a project-specific live-reload script. section 9.10 section 9.6.3 section 10.6.1




