When testing a single file with Jest, the key steps can be broken down into the following sections:
1. Installing Jest
First, ensure Jest is installed in your project. If not, install it using npm or yarn:
bashnpm install --save-dev jest
or
bashyarn add --dev jest
2. Configuring Jest
Ensure your project includes a configuration file (e.g., jest.config.js or the Jest configuration in package.json). In this file, set parameters to meet your testing needs. For example:
javascript// jest.config.js module.exports = { verbose: true, };
3. Writing Tests
For the file you want to test, create the corresponding test file. For instance, if your source file is sum.js, name your test file sum.test.js.
javascript// sum.js function sum(a, b) { return a + b; } module.exports = sum; // sum.test.js const sum = require('./sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
4. Running Tests
To run tests for sum.test.js alone, use the --testPathPattern option in Jest from the command line. This option makes Jest execute only files matching a specific pattern.
bashjest --testPathPattern=sum.test.js
This command locates and executes all test files matching sum.test.js.
Example
Suppose you have a project with a simple array operation function and its tests. The function file is arrayOps.js, and the test file is arrayOps.test.js.
javascript// arrayOps.js function getMax(arr) { return Math.max(...arr); } module.exports = getMax; // arrayOps.test.js const getMax = require('./arrayOps'); test('get max of [1, 3, 2] to equal 3', () => { expect(getMax([1, 3, 2])).toBe(3); });
To test this file, run:
bashjest --testPathPattern=arrayOps.test.js
This approach allows you to focus on individual file testing, facilitating modular testing in large projects while maintaining test independence and efficiency.