2021-11-21
|~2 min read
|249 words
I like to write most of my code in Typescript these days, so when I had an opportunity to start a new project recently, I wanted to make sure that I was configuring my tests to take advantage of that.
Since I am a fan of Jest, I thought I’d look to see if there was a better approach for Typescript. ts-jest seems like a great answer and the configuration was a breeze.
Consider this another entry in my ongoing series on configuring jest.
npm install --save-dev jest typescript ts-jest @types/jestts-jest has a built-in initialization function:
npx ts-jest config:initThis will create a jest.config.js:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
}However, I wanted to stay as close to native jest as possible, so I used jest’s initialization instead:
npx jest --initWith this, a jest.config.js file is created, which is easily modified to use ts-jest.
When taking this approach there are two things you need to remember:
Say no to using typescript in the CLI. When answering yes, the CLI will assume you’re using babel, which is an alternative way of using Typescript with Jest (though there are limitations1)
In the jest.config.js produced by jest --init, add in the preset ts-jest:
module.exports = {
// ...
preset: "ts-jest",
}ts-jest in the first place!Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!