我正在尝试在 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/