When using Jest for unit testing, there are several methods to run a single test or a specific set of tests.
1. Using test.only or it.only
If your test code contains multiple tests (using it or test functions), you can add .only to the test you want to run exclusively, so Jest will execute only that test. For example:
javascripttest('This is a regular test', () => { expect(true).toBe(true); }); test.only('This will be the only test run', () => { expect(true).toBe(true); }); test('This is another regular test', () => { expect(true).toBe(true); });
In the above code, only the test marked with test.only will be executed.
2. Using Jest command-line option --testNamePattern or -t
You can use Jest's command-line option --testNamePattern or its shorthand -t to run tests matching a specific name. This enables partial matching of the test name. For example, if you want to run only the test named 'This will be the only test run', you can use the command line:
bashjest --testNamePattern="This will be the only test run"
Or using the shorthand:
bashjest -t "This will be the only test run"
3. Using the filename
If you want to run a specific test file, you can specify the filename directly after the jest command:
bashjest path/to/your/test/file.test.js
This will execute all tests within the specified test file.
Example Scenario
Suppose you are developing an e-commerce application and have a test file for testing the functionality of adding items to the shopping cart. If you want to quickly verify that the 'Add single item' functionality works correctly without running all tests in the file, you can add test.only before the test or use the -t option to run only that test. This saves time, especially during early development when you might need to frequently run specific tests to verify code changes.
Using these methods effectively controls the scope of test execution, making unit testing more efficient and targeted in large projects.