在运行jest测试的时候为何报错:SyntaxError: Cannot use import statement outside a module?

在我的测试项目中:
image.png

// test001.ts
export function mySum(a:number, b: number) {
  return a + b 
}

mySum(11, 22)


// test/unit/test001.spec.ts
import mySum from '../../test001'

describe('calculate function', () => {
  it('', () => {
    expect(mySum(11, 22)).toEqual(33)
  })
}

但是在运行npm run test的时候报错:

$ npm run test

> my-app@0.1.0 test
> jest

 FAIL  test/unit/test001.spec.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:

    /Users/dele/Desktop/Test/js/typescript/ts-test01/my-app/test/unit/test001.spec.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { mySum } from '../../test001';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

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

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.136 s
Ran all test suites.
阅读 2.9k
2 个回答

1.用 Jest 的 transform 配置选项。在 Jest 配置文件( jest.config.js)里加一个 transform 选项,指定一个用来转换你代码的模块。用 babel-jest 来转换代码。

2.你用的是 TS,你也可以用 ts-jest。你可以在 Jest 配置文件中加一个 preset 选项,设为 'ts-jest'。

新手上路,请多包涵

com.example.lweicheng.splash.GsonTest 我上传的manifest文件有显示

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏