FreePhoenix888
FreePhoenix888

Reputation: 6087

How to fix Cannot use import statement outside a module when calling jest tests?

I am trying to run unit-tests for TypeScript files by using jest but it does not work

Error

freephoenix888@freephoenix888:~/Programming/test$ npx jest

> [email protected] test
> jest

 FAIL  ./sum.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /home/freephoenix888/Programming/test/sum.test.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { sum } from "./sum";
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1449:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.379 s
Ran all test suites.

How to reproduce

  1. Init npm project
freephoenix888@freephoenix888:~/Programming/test$ npm init -y
Wrote to /home/freephoenix888/Programming/test/package.json:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
  1. Install typescript
freephoenix888@freephoenix888:~/Programming/test$ npm install --save-dev typescript

added 1 package, and audited 2 packages in 10s

found 0 vulnerabilities
  1. Install jest
freephoenix888@freephoenix888:~/Programming/test$ npm install --save-dev jest

added 277 packages, and audited 279 packages in 41s

29 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
  1. Install @types/jest
freephoenix888@freephoenix888:~/Programming/test$ npm install --save-dev @types/jest

added 8 packages, and audited 287 packages in 4s

29 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
  1. Create sum.ts with this content:
export function sum({firstNumber, secondNumber} : {firstNumber: number , secondNumber: number}) {
   return firstNumber + secondNumber;
}
  1. Create sum.test.ts with this content:
import { sum } from "./sum"

test('sum', () => {
   expect(
      sum({
         firstNumber: 5,
         secondNumber: 5
      })
   ).toBe(10)
})
  1. Run npx jest command
freephoenix888@freephoenix888:~/Programming/test$ npx jest

> [email protected] test
> jest

 FAIL  ./sum.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /home/freephoenix888/Programming/test/sum.test.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { sum } from "./sum";
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1449:14)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.379 s
Ran all test suites.

Upvotes: 4

Views: 4506

Answers (1)

FreePhoenix888
FreePhoenix888

Reputation: 6087

How to fix

  1. Create a config for jest
npx ts-jest config:init
  1. Run npx jest and see that your tests are running
freephoenix888@freephoenix888:~/Programming/test$ npx jest
ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.
 PASS  ./sum.test.ts
  ✓ sum (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.328 s
Ran all test suites.

How to use jest.config with ts extension

If we try to change jest.config's extension to ts and run npx jest command we will get this error message:

freephoenix888@freephoenix888:~/Programming/test$ npx jest
Error: Jest: Failed to parse the TypeScript config file /home/freephoenix888/Programming/test/jest.config.ts
  Error: Jest: 'ts-node' is required for the TypeScript configuration files. Make sure it is installed
Error: Cannot find package 'ts-node'
  1. Install ts-node
npm install --save-dev ts-node
  1. Run npx jest and see that your tests are running
freephoenix888@freephoenix888:~/Programming/test$ npx jest
ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.
 PASS  ./sum.test.ts
  ✓ sum (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.328 s
Ran all test suites.

Upvotes: 1

Related Questions