AUTHOR
Daniel Strong, Frontend Engineer
Daniel is a Frontend Engineer at Codiga.
He is a passionate frontend engineer, teacher, and learner. He has worked on or led several creative projects where he's grown his leadership, management, design, and programming skills.
What is a Jest focus test
Jest is a popular JavaScript testing framework that allows developers to write and run tests for their code.
One of its features is the ability to "focus" a test by adding the .only
method to the test function. This tells Jest to only run that specific test and not any other tests in the file.
describe("my tests", () => {
test("this test will not run", () => {
// test code here
});
test.only("this test will run", () => {
// test code here
});
});
In the above example, we focused a single test within a test suite, but you can also attach .only
on a describe test suite to achieve something similar.
describe("NO tests in this suite will run", () => {
test("yay", () => {
// test code here
});
});
describe.only("ALL tests in this suite will run", () => {
test("nay", () => {
// test code here
});
});
When should you focus a Jest test
Focusing a test with .only
is useful when you're working on a specific feature or function and want to run only the relevant test.
Additionally, it can also be useful when you're trying to isolate a specific test that is failing and you want to run only that test to see if it is the only one that is failing or if it may be causing other tests to fail or vice versa.
Potential issues with focusing a Jest test
While this can be useful when working on a specific feature or function, it can also lead to issues if you accidentally commit a file with a focused test in it. In this case, you and any other developers on your team would only be running a subset of the test suite in the future.
Automatically check for Jest focused tests
Codiga provides IDE plugins and integrations with GitHub, GitLab, or Bitbucket to detect when you are using Jest focused tests. The Codiga static code analysis detects this issue directly in your IDE or code reviews.
This rule generates a warning when it detects a focused test.
To use this rule consistently, along with many other Jest best practices, all you need to do is to install the integration in your IDE (for VS Code or JetBrains) or code management system and add a codiga.yml
file at the root of your project with the following content:
rulesets:
- jestjs
You can also navigate to your project directory in your terminal and run the following command to get started.
npx @codiga/cli ruleset-add jestjs
It will then check all your Javascript and Typescript Jest files against 5+ Jest rules.
Prevent pushing Jest focuses tests to your repository
In addition to being covered in your IDE and during code reviews, Codiga also has a pre-push
Git hook to help ensure you don't git push
a focused test to your repository.