[英]Jest tests fail when trying to import date-fns in Angular project
I recently updated one of my Angular projects to Angular 13. After the updates I got some weird errors when trying to run the unit tests in the project.我最近将我的 Angular 项目之一更新为 Angular 13。更新后,我在尝试在项目中运行单元测试时遇到了一些奇怪的错误。
I created a minimal example inside a fresh Angular project to reproduce this behavior:我在一个新的 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');
});
});
When i execute npm run test
the test fails and produces the following output:当我执行
npm run test
时,测试失败并产生以下 output:
/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)
This is my jest.config.js
:这是我的
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>/'
})
};
And this my tsconfig.spec.json
:这是我的
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"
]
}
Any help is appreciated!任何帮助表示赞赏!
I solved my problem by adding date-fns
and .mjs
to the transformIgnorePatterns
as suggested in the jest-preset-angular migration guide .按照jest-preset-angular migration guide中的建议,我通过将
date-fns
fns 和.mjs
添加到transformIgnorePatterns
解决了我的问题。
module.exports = {
// ...other options
transformIgnorePatterns: ['<rootDir>/node_modules/(?!(.*.mjs)|date-fns)']
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.