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