【发布时间】:2021-03-22 14:24:39
【问题描述】:
我使用 Angular (2+) 开发了一个应用程序,现在我正在测试每个应用程序 .ts 文件以获得良好百分比的代码覆盖率。
我有个问题。我正在测试一个组件,它在ngOnInit 生命周期方法中使用document 对象来引用HTML 模板的某些元素。这是一个代码示例:
export class MyComponent implements OnInit {
element;
ngOnInit() {
this.element = document.getElementById('myElementId');
this.element.className = 'blur'
}
}
其中myElementId 是我模板的<div> 元素。
至于测试,下面是部分代码:
describe('MyComponent Tests', () => {
let fixture: ComponentFixture<MyComponent>;
let component: MyComponent;
let rootElement: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [MyComponentModule, RouterTestingModule],
providers: [],
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
})
});
});
beforeEach(() => {
fixture = TestBed.createComponent(IndexPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
rootElement = fixture.debugElement;
});
it("Should created", fakeAsync(() => {
expect(component).toBeTruthy();
}));
});
当我开始测试时,它给了我一个失败的结果,并出现以下错误:无法将属性“className”设置为 null。基本上fixture.detectChanges() 行激活了我的组件的ngOnInit() 方法,但是就好像测试文件上的组件实例没有与HTML 模板链接!。
由于这个原因,this.element.className = 'blur' 行是组件功能的基础,它被评估为一个空指针。
如何解决这个问题并很好地测试组件?
【问题讨论】:
标签: angular unit-testing testing jasmine karma-jasmine