我正在使用 jest 框架对我的 Angular 应用程序进行单元测试。我想我在使用 zone.js 的 test.ts 文件中遇到了问题。
我得到错误堆栈跟踪
TypeError: Cannot read property 'prototype' of undefined
3 | import { getTestBed } from '@angular/core/testing';
4 | import 'zone.js/dist/zone-testing';
> 5 | import {
| ^
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
at __extends (node_modules/zone.js/dist/zone-testing.js:394:73)
at node_modules/zone.js/dist/zone-testing.js:530:9
at node_modules/zone.js/dist/zone-testing.js:619:7
at node_modules/zone.js/dist/zone-testing.js:620:3
at Object.<anonymous>.NEWLINE (node_modules/zone.js/dist/zone-testing.js:9:65)
at Object.<anonymous> (node_modules/zone.js/dist/zone-testing.js:12:2)
at Object.<anonymous> (src/test.ts:5:1
我正在寻找一种以最少的代码更改来解决此问题的方法。
我已经尝试过适应中给出的解决方案
https://github.com/AlexanderZaytsev/react-native-i18n/issues/233
和
Jest: TypeError: Cannot read property of undefined没有任何运气。
此外,我已经尝试过文档,但它没有指定与此相关的任何内容,或者我错过了它。
这是我的test.ts 文件。
import { getTestBed } from '@angular/core/testing';
import 'zone.js/dist/zone-testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: any;
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
我已经使用了compilerOptions
,
"esModuleInterop": true,
"module": "es2015",
正如我所说的,我正在寻找一种只需更改最少的代码即可解决此问题的方法。感谢您的帮助。
最佳答案
如果您已经完全迁移到 Jest,您可以删除 test.ts,因为不再需要它,因为您不再使用 Jasmine 和 Karma。你可以阅读here .
另外,确保从 tsconfig.spec.ts 中删除它的引用。
如果出于某种原因,你需要保留它,你可以在 Jest 配置中忽略 test.ts 文件,因为默认情况下 jest 将测试所有以 spec.ts/js 和 test.ts/js 结尾的文件。
**Default configuration:**
testMatch: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]
**Change to:**
testMatch: [ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.spec).[jt]s?(x)" ]
您可以阅读有关配置 Jest 的更多信息 here
关于angular - 类型错误 : Cannot read property 'prototype' of undefined using jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56018191/