The Jest Config File
Explore the various options for configuring Jest for your specific application and the different ways to set up the configuration.
Configuration methods
Jest accepts the following three methods for its configuration:
- Write the settings directly in the application’s
package.json
file. - Write the settings in
jest.config.js
orjest.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 include a complete list below with brief descriptions.
clearMocks:
This is of the boolean
type, and its default is false
. We will dive deep into mocks at a later point, but we only need to know two things for now:
-
Mocks are a tool for controlling and replicating certain behavior, such as an API call or a third-party SDK. These API calls or third-party SDKs will either not work in a testing environment by nature, ...