Mastering Jest: Run All, Specific, and Coverage Tests with npm Scripts
This guide explains how to configure Jest test scripts in a package.json file and use npm commands to run the full test suite, generate coverage reports, watch for changes, and target individual test files or cases for faster, more focused development.
Introduction
In modern software development, testing ensures code correctness. Jest is a popular JavaScript testing framework. This guide shows how to configure test scripts in package.json and run them with npm.
Understanding test scripts in package.json
A package.json file typically contains a scripts section where commands are defined. Example scripts:
"scripts": {
"test": "jest",
"test:coverage": "jest --coverage",
"test:coverage:watch": "jest --coverage --watch",
"test:coverage:unit": "jest --coverage --testPathPattern='tests/unit'",
"test:coverage:integration": "jest --coverage --testPathPattern='tests/integration'",
"test:coverage:contract": "jest --coverage --testPathPattern='tests/contract'"
}The test script runs npm test, which executes jest and runs all test files found in the project.
The test:coverage script adds the --coverage flag, generating a coverage report that shows which parts of the code were exercised.
The test:coverage:watch script adds --watch, making Jest re‑run relevant tests automatically when files change, providing fast feedback during development.
Running specific tests
Running the entire suite can be slow, so Jest offers flags to narrow the scope. The --testPathPattern flag limits execution to files matching a given path. For example, npm run test:coverage:contract runs only tests under tests/contract/.
To run a single test file directly: npx jest tests/contract/auth-signin.test.ts To run a single test case inside a file, use the -t (or --testNamePattern) flag:
npx jest -t 'should succeed with correct credentials'Combining file path and test name gives the most precise execution:
npx jest tests/contract/auth-signin.test.ts -t 'should succeed with correct credentials'The following diagram visualizes the hierarchy from running all tests down to a single test case:
Conclusion
Jest’s flexibility, combined with well‑defined npm scripts in package.json, lets developers run all tests, generate coverage reports, watch for changes, or target individual files and test cases, enabling efficient and focused development.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
