How Do I Test a Single File Using Jest?

Better Stack Team
Updated on April 4, 2024

To test a single file using Jest, you can follow these steps:

Install Jest

If you haven't installed Jest yet, you can install it using npm:

 
npm install --save-dev jest

Create a Jest Configuration (Optional)

You can create a Jest configuration file (e.g., jest.config.js) to specify your test file patterns, test environment, and other configurations. If you don't create a configuration file, Jest will use its defaults.

Example jest.config.js:

 
module.exports = {
  testEnvironment: 'node', // Use 'node' for Node.js environment
  testMatch: ['<rootDir>/path/to/testfile.test.js'], // Adjust the path to your test file
};

Write Your Test File

Create your test file. Jest identifies test files based on their filename. For example, if your module is in a file named math.js, the corresponding test file should be named math.test.js or math.spec.js.

 
// math.test.js
const { add, subtract } = require('./math');

test('add function', () => {
  expect(add(2, 3)).toBe(5);
});

test('subtract function', () => {
  expect(subtract(5, 2)).toBe(3);
});

Run Jest

Run Jest using the following command in your terminal:

 
npx jest

Jest will run the tests and report the results. If you want to run a specific test file, you can provide the path to that file as an argument:

 
npx jest path/to/your/testfile.test.js

Jest will execute the specified test file and provide the test results.

That's it! Jest will automatically detect and run your test file. The expect function is used for assertions in Jest, and it provides various matchers for different types of assertions. Adjust the test file and configuration according to your project's needs.