How to Run Individual Tests in Jest from the Terminal

Testing is an integral part of modern web development. It ensures that your code behaves as expected and that new changes don’t break existing functionality. Jest is a JavaScript Testing Framework with a focus on simplicity, offers a way to run individual tests or suites directly from the terminal, making the testing process even more efficient. In this article, we will explore how to use npm test w to run specific tests by their description names.

Starting Jest in Watch Mode

Jest comes with a watch mode, which can be activated by appending the --watch flag to your test script in package.json. However, you can also activate it directly from the command line using the following command:

npm test -- --watch

Alternatively, you can use a shorthand for the watch flag:

npm test w

When you run this command, Jest enters the watch mode, which automatically reruns tests when it detects changes in your code.

Running Tests by Description

Once in watch mode, you’re presented with a usage guide and several options. One of these options is the ability to filter tests by their description names, also known as test names or titles.

To run tests by description, you can simply press p to filter by a filename regex pattern. Then, you can enter the description of the test you wish to run. Here’s an example:

Start Jest in watch mode:

npm test w

Press p to filter by a test name pattern.

Type the specific description or part of the test name you are looking for.

Jest will then run all tests that match the pattern you’ve typed. This feature is particularly useful when you’re working on a specific component or function and want to run only the relevant tests without triggering the entire suite.

Code Example: Running an Individual Test

Let’s say we have a test file for a function add:

describe('add function', () => {
it('adds two numbers correctly', () => {
expect(add(1, 2)).toBe(3);
});
});

To run only this test, you could enter the description ‘adds two numbers correctly’ after pressing p in watch mode.

Remember that the pattern you enter is case-sensitive and matches against the full description of the test as it appears in your test files. You can also use regular expressions for more complex patterns.

,