node.js - Hur åtgärdar man Cannot use import statement outside a module när man kör jest-tester?


Jag försöker köra enhetstester för TypeScript-filer med jest men det fungerar inte

Fel

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

> [email  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.

Hur man reproducerar

  1. Initiera npm-projekt
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. Installera typescript
freephoenix888@freephoenix888:~/Programming/test$ npm install --save-dev typescript

added 1 package, and audited 2 packages in 10s

found 0 vulnerabilities
  1. Installera 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. Installera @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. Skapa sum.ts med detta innehåll:
export function sum({firstNumber, secondNumber} : {firstNumber: number , secondNumber: number}) {
   return firstNumber + secondNumber;
}
  1. Skapa sum.test.ts med detta innehåll:
import { sum } from "./sum"

test('sum', () => {
   expect(
      sum({
         firstNumber: 5,
         secondNumber: 5
      })
   ).toBe(10)
})
  1. Kör npx jest-kommandot
freephoenix888@freephoenix888:~/Programming/test$ npx jest

> [email  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.

Svar #1

Hur man fixar

  1. Skapa en konfiguration för jest
npx ts-jest config:init
  1. Kör npx jest och se att dina tester körs
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.

Hur man använder jest.config med ts-tillägg

Om vi försöker ändra jest.configs filändelse till ts och köra kommandot npx jest får vi detta felmeddelande:

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. Installera ts-node
npm install --save-dev ts-node
  1. Kör npx jest och se att dina tester körs
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.

Relaterade artiklar