Use Jest with TypeScript
I love both Jest and TypeScript because they are awesome! And it will be great if we can combine both of them.
There are 2 ways to combine them together:
- Use
babel - Use
ts-jest
Use Babel
If you are a fan of babel, and you use it in the same project, you can choose this option. And it’s a simple process with 2 steps
-
Install preset
You can run the following command to install the preset for
TypeScriptyarn add -D @babel/preset-typescript
-
Add configuration
After you installed the preset, you can modify your babel configuration file to use the preset:
// babel.config.js module.exports = { presets: [ ["@babel/preset-env", { targets: { node: "current" } }], "@babel/preset-typescript", ], };
Use TS-Jest
If your project is purly on TypeScript , you probably don’t want to use babel just for Jest. Luckily there’s an npm package for you: ts-jest.
There are also 2 steps to do:
-
Install package
You can run the following command to install the package for
ts-jest.yarn add -D ts-jest @types/jestNote:
ts-jestis depending onJestandTypeScrip. And I assume you have already installedJestandTypeScriptin your project. -
Add configuration
Once the package is installed, you can run the following command to create the configuration file for
Jest:yarn ts-jest config:init
Summary
These 2 ways can both integrates Jest and TypeScript in your project. And you can enjoy using both of their super powers!
Happy coding!