【问题标题】:Jest tests fail when trying to import date-fns in Angular project尝试在 Angular 项目中导入 date-fns 时,Jest 测试失败
【发布时间】:2021-12-30 13:35:42
【问题描述】:

我最近将我的一个 Angular 项目更新为 Angular 13。更新后,我在尝试在项目中运行单元测试时遇到了一些奇怪的错误。

我在一个新的 Angular 项目中创建了一个最小示例来重现此行为:

import { format } from 'date-fns';
import { de } from 'date-fns/locale';


describe('AppComponent', () => {
  it('date-fns should work', () => {
    const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy', { locale: de });
    expect(result).toEqual('02/11/2014');
  });
});

当我执行npm run test 时,测试失败并产生以下输出:

/home/marco/dev/jest-test/node_modules/date-fns/esm/locale/index.js:2
    export { default as af } from "./af/index.js";
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      1 | import { format } from 'date-fns';
    > 2 | import { de } from 'date-fns/locale';
        | ^
      3 |
      4 | describe('AppComponent', () => {
      5 |   it('date-fns should work', () => {

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/app/app.component.spec.ts:2:1)

这是我的jest.config.js

const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');

module.exports = {
    preset: 'jest-preset-angular',
    roots: ['<rootDir>/src/'],
    testMatch: ['**/+(*.)+(spec).+(ts)'],
    setupFilesAfterEnv: ['<rootDir>/src/test.ts'],
    collectCoverage: true,
    coverageReporters: ['html'],
    coverageDirectory: 'coverage/my-app',
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
        prefix: '<rootDir>/'
    })
};

这是我的tsconfig.spec.json

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

感谢任何帮助!

【问题讨论】:

    标签: angular npm jestjs date-fns angular13


    【解决方案1】:

    按照jest-preset-angular migration guide 中的建议,我通过将date-fns.mjs 添加到transformIgnorePatterns 解决了我的问题。

    module.exports = {
        // ...other options
        transformIgnorePatterns: ['<rootDir>/node_modules/(?!(.*\\.mjs)|date-fns)']
    };
    

    【讨论】:

    • 感谢您分享您的答案!我对忽略模式进行了编辑,以包括文字“。”的转义。特点。如果我的编辑中断或无法作为解决方案,请随时恢复我的编辑。
    猜你喜欢
    • 2018-11-21
    • 1970-01-01
    • 2021-08-16
    • 2019-06-29
    • 2015-07-07
    • 2021-06-13
    • 2020-01-01
    • 1970-01-01
    • 2018-07-25
    相关资源
    最近更新 更多