乐闻世界logo
搜索文章和话题

How do I test a single file using Jest?

1个答案

1

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:

bash
npm install --save-dev jest

or

bash
yarn 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.

bash
jest --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:

bash
jest --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.

2024年6月29日 12:07 回复

你的答案