Невозможно импортировать целевой файл для тестирования из тестового файла (Angular, Jest) - PullRequest
0 голосов
/ 22 октября 2019

Я пытаюсь запустить юнит-тесты в приложении Angular, используя Jest.

/ projects / что-то / 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 /что-то / 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". Когда я пишу целевой код в тестовом файле (mylib.spec.js), он работает нормально и тест проходит, поэтому проблема, похоже, связана с оператором импорта.

Я ссылался на эту страницу, ноне мог решить это. Неожиданная ошибка токена при импорте Jest-тестов?

Любые предложения полезны.

...