Jest requires additional configuration to work with Typescript projects.
- Install the required dependencies:
$ npm install --save-dev jest babel-jest @babel/core @babel/preset-env ts-jest @types/jest
- Create the
babel.config.js
file in project root with the following content:
module.exports = {
presets: [["@babel/preset-env", { targets: { node: "current" } }]],
};
- If
jest.config.js
doesn't already exist in the project root, create it with the following content:
module.exports = {
preset: "ts-jest",
transform: {
"^.+\\.(ts|tsx)?$": "ts-jest",
"^.+\\.(js|jsx)$": "babel-jest",
},
};
- (Optional) Add the following to the
scripts
section of thepackage.json
file:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
}
While actively developing/testing certain features it's best to run the tests in watch mode, which causes them to re-run whenever a file changes.
To run tests in watch mode, use the following command:
$ npm run test:watch
To run tests once, use the following command:
$ npm test