无法导入目标文件以从测试文件(Angular,Jest)进行测试

时间:2019-10-22 08:35:31

标签: angular unit-testing jestjs

我正在尝试使用Jest在Angular应用中运行单元测试。

/projects/something/jest.config.js:

const tsJestPreset = require('jest-preset-angular/jest-preset').globals['ts-jest'];

module.exports = {
    globals: {
        'ts-jest': {
            tsConfig: 'src/tsconfig.spec.json'
        }
    },
};

/projects/streams/src/tsconfig.spec.json:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/spec",
    "types": [
//      "jasmine",
      "jest",
      "node"
    ]
  },
  "files": [
//    "test.ts",
    "polyfills.ts"
  ],
  "include": [
    "**/*.spec.ts",
    "**/*.d.ts",
    "**/*.spec.js"
  ]
}

要测试的文件(/projects/something/src/app/__tests__/mylib.js):

export function add(a, b) {
    return a + b;
}

测试文件(/ projects / something / src / app / __ tests __ / mylib.spec.js)

import { add } from 'mylib';

test('add 1 + 2', () => {
    expect(add(1, 2)).toBe(3);
});

但是,当我执行以下命令时:

jest mylib.spec.js

无法导入模块:

FAIL  src/app/__tests__/mylib.spec.js
● Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • 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/en/configuration.html

Details:

/projects/something/src/app/__tests__/mylib.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { add } from 'mylib';
                                                                                                ^

SyntaxError: Unexpected token {

  at ScriptTransformer._transformAndBuildScript (../../usr/local/share/.config/yarn/global/node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (../../usr/local/share/.config/yarn/global/node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        5.332s
Ran all test suites matching /mylib.spec.js/i.

当我执行“ ng test”时,它会产生相同的结果。 当我在测试文件(mylib.spec.js)中编写目标代码时,它可以正常运行并且测试通过, 因此问题似乎与import语句有关。

我参考了此页面,但无法解决。 Unexpected token 'import' error while running Jest tests?

任何建议都是有帮助的。

0 个答案:

没有答案