2

I am pretty new to TypeScript and I was experimenting with Jest (unit test framework). I was trying to make just a little and simple test, but I got a strange error.

Setup

I created a file position.ts in folder /src with the following code:

export class Position {
  constructor(public x: number, public y: number) {}
}

Then in folder /tests I put a file called position.test.ts:

import {Position} from './position';

test('basic', () => {
  let p = new Position(1, 2);
  expect(p.x).toBe(1);
  expect(p.y).toBe(2);
});

And I have created a file in the project root called jest.config.ts with the following content:

module.exports = {
  'roots': ['<rootDir>/src'],
  'transform': {'^.+\\.tsx?$': 'ts-jest'},
}

My tsconfig.json contains:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "./dist", 
    "rootDir": "./",
    "strict": true,
    "esModuleInterop": true
  }
}

Issue

When I run: tsc no errors are reported. When I run: npx jest I get the following error:

 FAIL  tests/position.test.ts
  ● Test suite failed to run

    /home/killkrt/developer/Atomts/tests/position.test.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Position } from '../src/position';
                                                                                             ^^^^^^
SyntaxError: Cannot use import statement outside a module

How can I solve it?

I would like to keep my source code in /src folder, tests in /tests and compiled js in /dist

Community
  • 1
  • 1
Kill KRT
  • 1,101
  • 2
  • 17
  • 37
  • 1
    https://stackoverflow.com/questions/56631104/jest-configure-typescript-without-webpack/56631145#56631145, please take a look. – Lidor Avitan Oct 07 '19 at 09:24
  • @LidorAvitan I have tried your link (that's basically what I was doing). Anyway I found a strange thing. I have tried with my Windows 10 machine and it works, while the same exact procedure doesn't work (same issue as already reported) on a fresh Arch Linux installation! Mmmh... – Kill KRT Oct 07 '19 at 14:14
  • Have you found the answer? I'm facing the same problem. Ubuntu – Anna Dec 04 '19 at 11:38
  • @Anna no :-( and I am not working anymore on that project, so no news – Kill KRT Dec 05 '19 at 13:50
  • There's similar issue. This may help. https://stackoverflow.com/a/59834203/6269336 – E. Evsevleev Jan 21 '20 at 15:29

2 Answers2

0

In my case I saw this error when I tried to run the tests using "Run" option in WebStorm.

But it works when I just ran command from console.

So the reason was - WebStorm used wrong jest configuration file by default. I changed it to point to the right one and this solve the issue for me.

Anna
  • 2,911
  • 6
  • 29
  • 42
0

Please follow the below steps:

yarn add ts-jest -D

then in your jest.config.js file put following:

module.exports = {
  transform: {
    '^.+\\.ts?$': 'ts-jest',
  },
};
ziishaned
  • 4,944
  • 3
  • 25
  • 32