typescript 如何修复调用jest测试时不能在模块外使用import语句?

fivyi3re  于 2022-12-30  发布在  TypeScript
关注(0)|答案(1)|浏览(249)

我尝试使用jest运行TypeScript文件的单元测试,但无法运行

错误

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

> test@1.0.0 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.

如何重现

1.初始化npm项目

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.安装 typescript

freephoenix888@freephoenix888:~/Programming/test$ npm install --save-dev typescript

added 1 package, and audited 2 packages in 10s

found 0 vulnerabilities

1.安装笑话

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.安装@类型/笑话

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.使用此内容创建sum.ts

export function sum({firstNumber, secondNumber} : {firstNumber: number , secondNumber: number}) {
   return firstNumber + secondNumber;
}

1.使用此内容创建sum.test.ts

import { sum } from "./sum"

test('sum', () => {
   expect(
      sum({
         firstNumber: 5,
         secondNumber: 5
      })
   ).toBe(10)
})

1.运行npx jest命令

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

> test@1.0.0 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.
brccelvz

brccelvz1#

如何修复

1.为jest创建配置

npx ts-jest config:init

1.运行npx jest并查看测试是否正在运行

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.

如何使用jest.configts扩展

如果我们尝试将jest.config的扩展名更改为ts并运行npx jest命令,我们会得到此错误消息:

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.安装ts-node

npm install --save-dev ts-node

1.运行npx jest并查看测试是否正在运行

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.

相关问题