Angular 测试无法读取 null 的属性 'ngModule'

标签 angular testng

我正在尝试在 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
我收到了这个错误:
类型错误:无法读取 null 的属性“ngModule”
版本之间有什么变化吗?
我正在使用最新版本的 angular 并且测试文件已使用命令 ng generate component 生成
我刚刚在描述后面添加了“f”和最新的“it”

最佳答案

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

ng test --include src/app/test-component/test-component.component.spec.ts
包括还有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 的一个用例将有不同的入口点文件用于需要为测试环境进行特殊配置的不同类型的测试。

关于Angular 测试无法读取 null 的属性 'ngModule',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64933850/

相关文章:

javascript - Angular Date 管道,以及一个带有 Momentjs 的简单计时器

node.js - 如何修复导出 'NotificationKind' 中未找到 'rxjs' 错误

angular - 在 Angular2 (AngularCLI) 中找不到模块 elasticsearch

Angular Google map 缩放仅工作一次,然后您无法更改缩放值

angular - 如何将 Angular2 RC1 与 systemjs bundle 在一起

java - Spring Mockito TestNG - 模拟在测试中持续存在

java - 如何将 log4j 与 TestNG 集成?

methods - 在 TestNG 中依次运行测试方法

Java TestNG 与跨多个测试的数据驱动测试

java - @DataProvider 和@BeforeMethod 命令