The Jest Config File
Understand how to set up the Jest config file using methods like package.json, jest.config.js, or CLI flags. Explore key configuration options including mock clearing, coverage reports, test environments, and more to customize Jest for your JavaScript testing needs.
Configuration methods
Jest accepts the following three methods for its configuration:
- Write the settings directly in the application’s
package.jsonfile. - Write the settings in
jest.config.jsorjest.config.ts, and place the file in the application root. - Write the settings in any file and identify the path/name with the CLI flag.
The package.json file
In this method, we only need to add the jest key at the top level of our application’s package.json file and point it to a JSON object of Jest configuration options. This option is illustrated below:
{
name: "my-app",
version: "0.1.0",
jest: {
clearMocks: true,
rootDir: "./"
}
}
The jest.config.js or jest.config.ts file
A separate configuration file is preferred. In this route, we add either a jest.config.js or jest.config.ts file to the root of our application and include all configuration options here. This would look like the following:
/// jest.config.js
module.exports = {
clearMocks: true,
rootDir: "./"
};
/// jest.config.ts (with ts-node installed)
import type { Config } from '@jest/types';
export default {
clearMocks: true,
rootDir: "./"
} as Config.InitialOptions;
The CLI flag
Last, we can include our configuration in a file with a name and location of our choosing. The file would look similar to the example in the previous method. However, it can be a JavaScript, TypeScript, CommonJS, ES Module, or JSON file type.
/// myJestConfiguration.json
{
clearMocks: true,
rootDir: "./"
};
We tell Jest where to find the configuration with its CLI flag, as shown below:
yarn jest --config myJestConfiguration.json
Popular configuration options
For this section, we’ll work inside the context of a jest.config.js file.
Jest offers a robust set of configuration options, allowing us to control everything from setting up testing coverage reports to globals to setup and teardown. We can structure Jest to the specific needs of our application. We are going to cover several popular configuration options in depth and ...