Jest With Typescript
Test-driven Typescript with ease
If you are a developer with a bit of experience with Typescript and unit test, this post is for you.
I was happy with Mocha and Chai until I started to use Typescript. In Typescripts’ setup with different ECMAScript or Babel versions, you may need various hacks to get it to work. Tooling is vital as other developers wouldn’t have frustration and obstacle because of the fragile and hacky solution that might be broken somewhere at a point in the future when tools and libraries are updated.
We’re gonna create the simplest setup of Typescript and Jest. In a blank new project, initiate with
$ yarn init -y
Then install typescript, jest, @types/jest, ts-jest as development dependencies.
$ yarn add -D typescript jest @types/jest ts-jest
Cool. Let’s have the bare minimal config.
First, generate typescript config with tsc.
$ tsc --init
Second, generate Jest config with ts-jest.
$ yarn ts-jest config:init
There you go! You’re ready to write the test. Straightforward enough?
If you run the command npx jest at this moment, of course we don’t have any test case yet, but you will see the default testMatch, testPathIgnorePatterns, and testRegex in your terminal. It is a nice hint of the path(s) being tested.
We’re gonna create a simple function sum to illustrate the test. Okay, we are test-driven developer, let’s create an empty test case first. In the root folder, make a new file dummy.test.ts and save with below test case. test and expect comes as global and you don’t need to import it!!
Sweet. Let’s run npx jest
Cool. Jest recognise our unit test.
Let create our function body and complete the test case. In the root folder, create dummy.ts with the followed function.
Then complete the test case.
Fantastic! Now your test case passes.
Congratulation! You can start test-driven Typescript in a comfortable fashion.
To sum up what we’ve done.
- Typescript and Jest minimal setup.
- A vanila unit test.
The complete source code can be found here. Cheers.
In case you need to add Jest on top of an existing Typescript project. You probably need to understand more the how to configure the test path(s).
A common practice in Typescript is to structure the .ts files under a source folder, say src, and the compiled files in a generated folder, say build. Let setup a bit further.
$ tsc --outDir build
Both tests in source and build has been executed!
To remove the duplication, you need to ignore the build/ folder for Jest. To achieve it, you might set your Jest
roots property to source/ folder in the jest.config.js by
Or define the
modulePathIgnorePatterns property in the same config file.
Beware you might use either one but not both!!