Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot setup jest with typescript

I'm following this example to set up some basic unit testing for a typescript project: https://dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln

I have a main.ts exporting a isInternalLink function

and a main.spec.ts that tries to test it

but I get the following error:

C:\data\devel\apps\tmp\jest-typescript\src\main.spec.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { isInternalLink } from './main.js';
SyntaxError: Unexpected token {
  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)

This is the public repo with the complete example: https://gitlab.com/opensas/jest-typescript

Can anybody point me in the right direction, or provide a working example?

like image 965
opensas Avatar asked Jan 25 '23 20:01

opensas


2 Answers

The Jest TypeScript documentation covers using babel to preprocess the TypeScript files, and also links to ts-jest.

To add ts-jest to your project, install ts-jest:

npm install --save-dev ts-jest

and add this to your package.json to preprocess the TypeScript files:

  "jest": {
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json"
    ]}

After doing this in your project I was able to run the tests:

$ npx jest
 PASS  src/main.spec.ts
  ✓ should return false given external link (2ms)
  ✓ should return true given internal link

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.096s, estimated 2s
Ran all test suites.
like image 109
shadowspawn Avatar answered Jan 31 '23 13:01

shadowspawn


Here is a demo use jestjs with typescript: https://github.com/mrdulin/jest-codelab

devDependencies of package.json:

"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"

In the root path of the project, create jest.config.js:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node'
};

That's all setup. You can find the documentation and follow the 4 steps here: https://github.com/kulshekhar/ts-jest#getting-started

like image 28
slideshowp2 Avatar answered Jan 31 '23 12:01

slideshowp2