I'm new to Typescript, jest.ts, and got.ts - I'm trying to create an API test, but I'm getting an
SyntaxError: Cannot use import statement outside a module
I can't figure out why this is happening. I've tried several fixes but failed on all of them.
Package.json
{
"type": "module",
"dependencies": {
"@types/got": "^9.6.12",
"got": "^12.5.1",
"ts-node": "^10.9.1"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@types/jest": "^29.1.2",
"ts-jest": "^29.0.3",
"typescript": "^4.8.4"
},
"scripts": {
"test-gotjest": "npx jest ./tests/gotjest"
}
}
jest.config.js
export default {
preset: 'ts-jest',
setupFilesAfterEnv: ["@testing-library/jest-dom"]
};
the actual test file itself - gotjest.test.ts
import { got } from "got";
import {describe, expect, test} from '@jest/globals';
describe('see if got works', () => {
test('get a cat fact', () => {
let foo = got.get('https://catfact.ninja/fact');
expect(3).toBe(3);
});
});
when I run the test with "npm run test-gotjest" I get the following:
SyntaxError: Cannot use import statement outside a module
> 1 | import { got } from "got";
| ^
2 | import {describe, expect, test} from '@jest/globals';
3 |
4 | describe('sum module', () => {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1678:14)
at Object.<anonymous> (tests/gotjest/gotjest.test.ts:1:1)
What am I missing? When I run with out got, the import statement for
import {describe, expect, test} from '@jest/globals';
works fine. Help!
I have found a solution mentioned in this GitHub issue: https://github.com/sindresorhus/got/issues/1952
TL:DR; downgrade to got v11 to interop with jest.