【问题标题】:Issue with Setting up Jest in angular 9 with angular-jest-preset使用 angular-jest-preset 在 angular 9 中设置 Jest 的问题
【发布时间】:2023-02-16 09:12:19
【问题描述】:

我目前正在使用 jest-preset-angular 版本 9 在 angular 9 中设置 Jest,代码运行但出现以下错误:

TypeError: Cannot read property 'ngModule' of null

不确定如何调试。

这是我的 jest.config.json

{
"preset": "jest-preset-angular",
"setupFilesAfterEnv": [
    "<rootDir>/setup-jest.ts"
],
"transformIgnorePatterns": [
    "node_modules/(?!@ngrx|ngx-socket-io)" 
],
"transform": {
    "^.+\\.(ts|js|html)$": "ts-jest"
},
"testPathIgnorePatterns": [
    "<rootDir>/node_modules/",
    "<rootDir>/dist/",
    "<rootDir>/src/test.ts"
],
"modulePaths": ["<rootDir>"]

}

和规格文件

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { myComponent } from './knowuser.component';

import 'zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/zone-testing';

describe('myComponent', () => {
  let component: myComponent;
  let fixture: ComponentFixture<myComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ myComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(myComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

【问题讨论】:

  • 纯 js 服务成功执行。它只是与组件我有问题
  • 您使用哪个命令来运行测试文件?

标签: angular jestjs ts-jest


【解决方案1】:

您看到的错误消息与 TestBed 配置有关。该错误表明 TestBed 正在为 ngModule 属性返回 null,这表明 Angular 模块配置设置不正确。

这个错误可能有几个不同的原因,但一个常见的原因是 TestBed.configureTestingModule() 方法配置不正确。

以下是您可以尝试的几件事:

  1. 检查正在测试的组件是否包含在 TestBed.configureTestingModule()1 method. In your spec file, you have correctly included the component in the declarations` 数组的 declarations 数组中,因此这似乎不是问题所在。
  2. 检查TestBed.configureTestingModule() 方法的imports 数组中是否包含被测组件的任何依赖项。如果此数组中不包含依赖项,则 ngModule 属性将为空。确保您已在 imports 数组中正确包含任何必需的模块。
  3. 确保您已经为 Jest 和 jest-preset-angular 安装了所有必要的包。该错误消息可能与丢失或安装不正确的软件包有关。
  4. 尝试从规范文件中删除 import 'zone.js' 行及其相关导入。 zone.js库已经包含在jest-preset-angular包中,所以你不需要单独导入它。

    如果这些解决方案均无效,请尝试发布完整的错误消息和任何其他相关代码或配置文件。

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2019-01-24
    • 2020-02-21
    • 2021-09-10
    相关资源
    最近更新 更多