
To get started with Jest, the first thing you need to do is install it. If you’re working on a Node.js project, you can easily add Jest to your project using npm. Just navigate to your project directory and run the following command:
npm install --save-dev jest
This command installs Jest as a development dependency. It’s a good practice to keep testing libraries as dev dependencies since they aren’t needed in the production environment. If you’re using Yarn, the command is equally straightforward:
yarn add --dev jest
Once Jest is installed, you can configure it in your project. Typically, this is done in the package.json file. Add a test script that specifies how to run Jest by adding the following line under the “scripts” section:
"scripts": {
"test": "jest"
}
Now, you can run your tests with a simple command:
npm test
This will execute Jest and look for test files in your project. By default, Jest will search for files with names that end in .test.js or .spec.js. If you want to customize the way your tests are discovered or executed, you can add a Jest configuration object either in your package.json or in a separate Jest configuration file. For instance:
{
"jest": {
"testMatch": [
"**/?(*.)+(spec|test).[jt]s?(x)"
]
}
}
With this setup, you’re ready to begin writing your tests. It’s essential to keep your test files organized, typically in a __tests__ directory or alongside the files they test. This organization helps maintain clarity in larger projects. Now, create your first test file, say, sum.test.js, and let’s write a simple test:
function sum(a, b) {
return a + b;
}
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Running this test is as simple as executing the test command again. If all goes well, you should see Jest indicating that your test has passed. If you encounter any issues, they could stem from various sources, such as incorrect file naming conventions or syntax errors in your test code. Remember, Jest is quite verbose with its output, so it should provide helpful clues to troubleshoot any problems.
Ailun Screen Protector for iPad 11th A16 2025 [11 Inch] / 10th Generation 2022 [10.9 Inch], Tempered Glass [Face ID & Apple Pencil Compatible] Ultra Sensitive Case Friendly [2 Pack]
$7.98 (as of June 3, 2026 23:09 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Running your first test command
To run your first test, you simply execute the command you set up earlier:
npm test
Upon running this command, Jest will automatically look for any test files in your project. By default, it will scan for files that match the patterns specified earlier, like *.test.js or *.spec.js. If it finds your sum.test.js file, it will execute the tests defined within it. You should see output in your terminal that indicates whether the tests passed or failed.
If you want to run a specific test file rather than all tests, you can do so by providing the path to that file in the command. For example:
npx jest sum.test.js
This command runs only the tests in sum.test.js. The npx command allows you to run Jest without needing to install it globally, which is beneficial for keeping your environment clean.
Jest provides a variety of command line options that can help you customize how tests are run. You can use the --watch option to run tests in watch mode, which means Jest will re-run your tests whenever it detects changes in your files. This is particularly useful during development:
npx jest --watch
You can also utilize the --coverage option to generate a coverage report, which indicates how much of your code is covered by tests. This is a great way to identify untested parts of your codebase:
npx jest --coverage
Coverage reports can help ensure that you maintain a healthy test suite as your application grows. Additionally, you can specify which tests to run based on a pattern using the -t or --testNamePattern option. For instance:
npx jest -t 'adds 1 + 2'
This command will run only the test that matches the name pattern you provided. It’s a handy way to focus on specific tests during development.
As you delve deeper into Jest, you may encounter some common issues. One frequent problem is related to the environment in which your tests are running. Jest runs in a Node.js environment by default, but if your tests depend on browser-specific features, you might need to use Jest’s built-in support for simulating a browser environment through the jsdom package. You can configure this in your Jest settings:
{
"jest": {
"testEnvironment": "jsdom"
}
}
Another common issue is related to asynchronous tests. If your tests involve asynchronous operations, such as API calls or timers, you need to ensure that Jest knows when your test has completed. You can achieve this using the async/await syntax or by returning a promise from your test function:
test('async test example', async () => {
const data = await fetchData();
expect(data).toBeDefined();
});
By following these guidelines and utilizing the various command line options Jest provides, you can effectively manage and run your tests. The more you practice, the more comfortable you’ll become with Jest’s capabilities and nuances. Remember that testing is not just about writing tests, but also about understanding how to run and troubleshoot them efficiently. This mindset will pay off as your projects scale and evolve.
Exploring command line options for Jest
The --watch flag is smart; it uses your source control information (like Git) to figure out which files have changed and only runs the tests related to those files. This is incredibly efficient. However, sometimes you want to re-run all tests whenever any file changes. For that, you use --watchAll. It’s less efficient but can be useful if Jest’s dependency graph gets confused or if you’ve made changes that aren’t tracked by Git, like installing a new dependency.
npx jest --watchAll
Another crucial option for debugging is --runInBand or its shorthand, -i. By default, Jest runs your test files in parallel across multiple worker processes to speed things up. This is great for performance, but it makes debugging a nightmare. If you’re trying to use a debugger or if your tests are conflicting with each other (perhaps they’re fighting over a database or a file), running them serially is the way to go. It will be slower, but your logs and debugger statements will make sense.
npx jest --runInBand
Sometimes, things just go wrong. Your tests were passing, you didn’t change anything, and now they’re failing with bizarre errors. Before you spend hours pulling your hair out, try clearing Jest’s cache. Jest caches information about your project structure and transformed files to speed up test runs. This cache can occasionally get corrupted. The --clearCache option is your friend here.
npx jest --clearCache
After clearing the cache, run your tests again. You’d be surprised how often this fixes inexplicable problems. For more targeted testing, especially in a CI/CD environment, you might want to run tests only for the code you’re about to commit. The --findRelatedTests option lets you do just that. You pass it a list of source files, and it will intelligently run only the test files that depend on them.
npx jest --findRelatedTests src/components/Button.js src/utils/helpers.js
Moving on from the command line, let’s talk about some common headaches you’ll encounter. A frequent source of pain is module resolution, especially if you’re using path aliases in your project, which is common in frameworks like Vue or React with Webpack/Vite. Your application code might have nice, clean imports like import MyComponent from '@/components/MyComponent'. This works fine in your app’s build process, but Jest has no idea what @/ means, so it will throw a “Cannot find module” error. To fix this, you need to tell Jest how to resolve these paths using the moduleNameMapper option in your Jest configuration file (jest.config.js or in package.json).
// jest.config.js
module.exports = {
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
}
};
This regular expression tells Jest that any import starting with @/ should be mapped to the src directory at the project’s root. Getting this configuration right is essential for a smooth testing experience in modern JavaScript projects.
Another wall developers hit is debugging the tests themselves. Placing a debugger statement in your test code and running npm test won’t work as you expect, because the tests are running in a separate Node.js process that isn’t connected to your browser’s or IDE’s debugger. To properly debug a Jest test, you need to launch Node with the inspector flag and tell Jest to run in the same process using --runInBand.
node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand your-test-file.test.js
This command starts the test process but pauses it before execution, allowing you to attach a debugger (like the one in Chrome DevTools or VS Code). The --runInBand flag is critical here; without it, Jest would spawn worker processes that the debugger wouldn’t be attached to. Once you’re attached, you can step through your test code, inspect variables, and figure out what’s going wrong.
Flaky tests caused by timers are another common nuisance. If you have code that uses setTimeout or setInterval, your tests might become slow and unreliable. Jest provides a brilliant solution for this: fake timers. By calling jest.useFakeTimers() at the beginning of your test, you can replace the native timer functions with mock implementations that you control.
test('calls callback after 1 second', () => {
jest.useFakeTimers();
const callback = jest.fn();
doSomethingThatSetsATimeout(callback, 1000);
// At this point, the callback has not been called yet
expect(callback).not.toHaveBeenCalled();
// Fast-forward time by 1000ms
jest.advanceTimersByTime(1000);
// Now the callback should have been called
expect(callback).toHaveBeenCalledTimes(1);
});
This allows you to test time-dependent logic instantly without actually waiting. You can advance time by a specific amount with jest.advanceTimersByTime() or run all pending timers immediately with jest.runAllTimers(). This makes your tests deterministic and lightning-fast. Just remember to call jest.useRealTimers() if you need to restore the original timers within the same file for other tests.
