Jest/Ionic 4 beta - 从"@ionic/角度"导入{平台};获取语法错误:在 Jest 测试中意外导出令牌,而不是 Ionic



对基本包运行 Jest 时,我在运行测试时收到 Jest 错误,当简单地运行ionic serve时不会出现该错误。 开玩笑在

import { Platform } from '@ionic/angular';

即:

export { IonicModule } from './ionic-module';
^^^^^^
SyntaxError: Unexpected token export
3 | import { RouterTestingModule } from '@angular/router/testing';
4 |
> 5 | import { Platform } from '@ionic/angular';
| ^
6 | import { SplashScreen } from '@ionic-native/splash-screen/ngx';
7 | import { StatusBar } from '@ionic-native/status-bar/ngx';
8 |
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (src/app/app.component.spec.ts:5:1)

My Jest.config.json

module.exports = {
collectCoverage: true,
collectCoverageFrom: [
"src/**/*.ts"
],
coverageDirectory: "<rootDir>/coverage/",
moduleNameMapper: {
"@core/(.*)": "<rootDir>/src/app/core/$1",
"@state/(.*)": "<rootDir>/src/app/state/$1"
},
preset: "jest-preset-angular",
roots: ['src'],
setupTestFrameworkScriptFile: "<rootDir>/src/setup-jest.ts",
transformIgnorePatterns: [
"node_modules/(?!(@ionic-native|@ionic|angularfire2)/)"
],
verbose: false  
}

我只是使用示例侧菜单模板并调整组件以运行 Jest。

看到所有答案都很长,我决定在阅读 Jest 单元测试不再适用于 Ionic 4 后展示对我有用的东西。

要使其工作,您需要添加到jest.config.ts

transformIgnorePatterns: [
"node_modules/(?!@ionic-native|@ionic)"
],

tsconfig.spec.json集中:

"compilerOptions": {
"allowJs": true,
},

当某些文件需要预处理才能在 Jest 中使用时,会出现此问题。在这种情况下,离子导入需要预处理,但通常通过transformIgnorePatterns忽略。但这只是问题的一半。我们还需要添加一些 babel 来处理文件,以便它们可以运行。

我能够通过使用以下配置添加一个 .babelrc 文件来解决此问题

{ 
"presets": [["@babel/preset-env", {
"modules": "commonjs",
"targets": {
"node": "current"
}
}]],
"plugins": ["transform-export-extensions", "@babel/plugin-transform-runtime"]
}

我使用了以下开玩笑的配置

{
"jest": {
"preset": "jest-preset-angular",
"setupTestFrameworkScriptFile": "<rootDir>/src/setup-jest.ts",
"globals": {
"ts-jest": {
"tsConfigFile": "tsconfig.jest.json",
"useBabelrc": true
},
"__TRANSFORM_HTML__": true
},
"transformIgnorePatterns": [
"node_modules/(?!@ngrx|angular2-ui-switch|ng-dynamic|@ionic|@ionic-native)"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
]
}
}

src/tsconfig.spec.json也需要一些小的调整。

{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"baseUrl": "./",
"module": "commonjs",
"allowJs": true,
"types": [
"jest",
"jquery",
"jsdom",
"node"
]
}, 
"include": [
"polyfills.ts",
"**/*.spec.ts",
"**/*.d.ts"
]
}

你的回答对我不起作用。但是,我注意到删除多余的括号可以消除错误。 尝试更改:

transformIgnorePatterns: [
"node_modules/(?!(@ionic-native|@ionic|angularfire2)/)"
],

transformIgnorePatterns: [
"node_modules/(?!@ionic-native|@ionic|angularfire2)"
],

不过,对我来说,这现在带来了一个新的错误:

Cannot find module '@ionic/core/loader' from 'app-initialize.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (node_modules/@ionic/angular/dist/app-initialize.js:1:1)

在我升级到 Ionic 4 beta 11(从 beta 8(之前,这一切都运行良好。我现在也在使用 Jest 23.6.0,但它在 Jest 23.5.0 中也失败了。

无论是否使用您的babelrc配置,我都会收到这些错误。

作为参考,这是我ionic info

Ionic:
ionic (Ionic CLI)          : 4.1.2
Ionic Framework            : @ionic/angular 4.0.0-beta.11
@angular-devkit/core       : 0.8.3
@angular-devkit/schematics : 0.8.3
@angular/cli               : 6.2.3
@ionic/ng-toolkit          : 1.0.7
@ionic/schematics-angular  : 1.0.6
Cordova:
cordova (Cordova CLI) : 7.1.0
Cordova Platforms     : none
Cordova Plugins       : no whitelisted plugins (0 plugins total)
System:
Android SDK Tools : 26.1.1 (/Users/rc101077/Library/Android/sdk)
ios-deploy        : 2.0.0
ios-sim           : 7.0.0
NodeJS            : v8.11.4 (/Users/rc101077/.nvm/versions/node/v8.11.4/bin/node)
npm               : 6.4.1
OS                : macOS High Sierra
Xcode             : Xcode 9.4.1 Build version 9F2000

就我而言,对于Ionic 5,Angular 10和NX monorepo,我必须执行以下操作才能启用Ionic应用程序的Jest测试。

注意:如果您已经有标准的 Jest 设置,请跳过前 4 个步骤。

注2:步骤顺序并不重要。

1. 删除所有 Karma 和 Jasmine 文件和依赖项

  • 删除karma.conf.jssrc/test.ts
  • package.json中删除与karmajasmine相关的所有内容(例如@types/jasminekarma等(

阿拉伯数字。添加开玩笑依赖项

添加jestjest-preset-angular@types/jestts-jest到您的devDependencies中,如果您还没有它们:

# if you use yarn:
yarn add --dev jest jest-preset-angular @types/jest ts-jest
# or if you use npm:
npm install --save-dev jest jest-preset-angular @types/jest ts-jest

3. 更新角度.json

更新您的angular.json文件。将 Karma 的architect->test配置替换为 Jest 的配置:

"test": {
"builder": "@nrwl/jest:jest",
"options": {
"jestConfig": "apps/my-app/jest.config.js",
"polyfills": "apps/my-app/src/polyfills.ts"
}
}

注意:我使用@nrwl/jest:jest生成器。如果您没有使用 NX monorepo,只需将@angular-builders/jest:run指定为构建器,然后从配置选项中删除"apps/my-app/"。

4. 创建测试设置。

创建具有单行内容的src/test-setup.ts文件:

import 'jest-preset-angular';

5. 添加 Babel 依赖项

babel-jest@babel/preset-env@babel/plugin-syntax-dynamic-import添加到您的devDependencies

# if you use yarn:
yarn add --dev babel-jest @babel/preset-env @babel/plugin-syntax-dynamic-import
# or if you use npm:
npm install --save-dev babel-jest @babel/preset-env @babel/plugin-syntax-dynamic-import

6. 更新 tsconfig.spec.json

"allowJs": truetypes添加到 TypeScript 配置中的compilerOptions。添加files以编译之前创建的test-setup.ts文件。

我的最终版本tsconfig.spec.json

{
"extends": "./tsconfig.json",
"compilerOptions": {
"allowJs": true,
"outDir": "../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

7. 创建或更新 jest.config.js

在应用根目录(您有package.json的位置(中创建jest.config.js(如果尚未创建(。

注意:我将transformIgnorePatternsglobal.ts-jest.babelConfig设置添加到Angular的默认Jest配置版本中。

该文件的最终版本如下所示:

const esModules = ['@ionic'].join('|');
module.exports = {
preset: '../../jest.preset.js',
coverageDirectory: '../../coverage/apps/mobile-ui',
snapshotSerializers: [
'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
'jest-preset-angular/build/AngularSnapshotSerializer.js',
'jest-preset-angular/build/HTMLCommentSerializer.js',
],
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'], // leave `<rootDir>` string as is
globals: {
'ts-jest': {
babelConfig: {
presets: [
[
'@babel/preset-env',
{ targets: { node: true }, modules: 'commonjs' }
]
],
plugins: ['@babel/plugin-syntax-dynamic-import']
},
tsConfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\.(html|svg)$',
astTransformers: {
before: [
'jest-preset-angular/build/InlineFilesTransformer',
'jest-preset-angular/build/StripStylesTransformer',
]
},
},
},
// To transform Ionic modules to UMD, because Jest can't import them otherwise
// (see here: https://medium.com/@gregor.woiwode/how-to-setup-jest-in-an-ionic-4-project-ff1e5b72dd79)
transformIgnorePatterns: [
`/node_modules/(?!${esModules})`
],
displayName: 'my-app',
};

感谢这篇文章,它帮助我确定了这些步骤:如何在 Ionic 4 项目中设置 Jest |格雷戈尔·沃伊沃德 |4月 25, 2019 |中等

最新更新