【问题标题】:Angular Test Cannot read property 'ngModule' of nullAngular 测试无法读取 null 的属性“ngModule”
【发布时间】:2020-11-21 02:54:34
【问题描述】:

我正在尝试在 Angular 上使用一个简单的测试,这里是测试的内容:

import { ComponentFixture } from '@angular/core/testing';
import { TestBed } from '@angular/core/testing';
import { By } from "@angular/platform-browser"
import { TestComponentComponent } from './test-component.component';

fdescribe('TestComponentComponent', () => {
  let component: TestComponentComponent;
  let fixture: ComponentFixture<TestComponentComponent>;

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

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

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

  it('should show no data', () => {
    fixture.detectChanges();
    const noDataDiv = fixture.debugElement.query(By.css('#noData'));
    expect(noDataDiv.nativeElement.textContent).toEqual('No Data');
  });
});

我通过这个命令运行测试:

ng test --main .\src\app\test-component\test-component.component.spec.ts

我得到了这个错误:

TypeError:无法读取 null 的属性“ngModule”

版本之间有什么变化吗?

我正在使用最新版本的 angular,并且测试文件已使用命令 ng generate component 生成

我刚刚在 describe 和最新的 'it' 后面添加了 'f'

【问题讨论】:

    标签: angular testng


    【解决方案1】:

    你不需要--main参数,你可以直接运行包含的文件:

    ng test --include src/app/test-component/test-component.component.spec.ts
    

    Include 还支持glob,您可以使用它在文件夹中运行测试:

    ng test --include src/**/*.spec.ts
    

    --main 参数是干什么用的?

    它用于为 Karma 定义 Angular 应用程序的入口点。这很重要,因为 Angular 需要在测试模式下启动,例如可以创建模块和组件。

    如果您查看项目中的angular.json,您会看到如下内容:

            "test": {
              "builder": "@angular-devkit/build-angular:karma",
              "options": {
                "main": "src/test.ts"
                ...
              }
            }
    

    main 标识符链接到文件src/test.ts,用于初始化测试环境:

    // First, initialize the Angular testing environment.
    getTestBed().initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting()
    );
    

    所以--main 的一个用例是为需要对测试环境进行特殊配置的不同类型的测试使用不同的入口点文件。

    【讨论】:

      猜你喜欢
      • 2021-01-13
      • 2020-07-09
      • 2020-11-16
      • 1970-01-01
      • 2019-08-09
      • 2020-06-13
      • 2014-10-31
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多