首页 > 解决方案 > TypeError:无法使用玩笑读取未定义的属性“原型”

问题描述

我正在使用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",

正如我所说,我正在寻找一种以最少的代码更改来解决此问题的方法。任何帮助表示赞赏。

标签: angulartypescriptunit-testingjestjs

解决方案


如果您已经完全迁移到 Jest,您可以删除 test.ts,因为您不再使用 Jasmine 和 Karma,因此不再需要它。你可以在这里阅读。

此外,请确保从 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的更多信息


推荐阅读