DEV Community

Unit Testing with Typescript and Jest

Muhammad Muhajir on November 09, 2018

Originally published in https://muhajirframe.com/writing/unit-test-typescript-jest/ In this article we'll try to cover a simple unit testing in ...
Collapse
 
kukuster profile image
Kukuster

Just wanted to say that it may not work right away.
For example, in VSCode doing Ctrl+Shift+P > TypeScript: Restart TS server helps, as sometimes it fails to recognize jest, or the test file to be a module, etc.
Also, for me, with this guide, I've had my VSCode failing to recognize test and expect functions in *.ts files, showing errors, even though it worked overall with npm run test, passing these 2 tests.
What helped me is to remove test files (here: "**/*.spec.ts") from "exclude" prop in tsconfig.json. Why would you do that in the first place? :)

Collapse
 
ivorcummings profile image
Ivor Scott

Nice article. I found it helpful, btw, in the article you say

npm run jest

but the script is called test.

Collapse
 
muhajirdev profile image
Muhammad Muhajir • Edited

Ah, nice find @ivorcummings . Now updated

Collapse
 
opensas profile image
opensas

I'm trying to follow your example but I get an Unexpected token { error then tring to impoet isInternalLink from main.spec.ts
Here's a question at SO: stackoverflow.com/questions/578390...
and the public repo with the example: gitlab.com/opensas/jest-typescript
What am I doing wrong?

Collapse
 
opensas profile image
opensas

Sorry, my fault, I used jest.config.ts instead of jest.config.js... great tutorial!

Collapse
 
justincalleja profile image
Justin Calleja

Nice post thanks! While following along, I had to add this to tsconfig.json to get it to work (after installing @types/jest):

  "types": ["node", "jest"]

Otherwise, I'd get:

Cannot find name 'test'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.
Collapse
 
js2me profile image
Sergey S. Volkov

Thanks for this article so I currently looking for good guide of jest integration with typescript for my library! Thanks!

Collapse
 
muhajirdev profile image
Muhammad Muhajir

No problem. Have a good a day :)

Collapse
 
ugeshgupta000 profile image
ugeshgupta000

jest.config.js is not shown in the file tree. Also, it would be nice if you explain what is the significance of various config files and their params.

Collapse
 
ctownshend profile image
Cameron Townshend

Clap for you Muhajir. Nice clean article.

Collapse
 
muhajirdev profile image
Muhammad Muhajir

Thanks bro

Collapse
 
pragnyanr profile image
PRAGNYA-NR

Awesome dude, u saved my time. TQ for posting.