问题的根本原因是在测试中无法找到所需的元素来进行断言或其他操作,从而导致了“TypeError: Cannot read property 'textContent' of null”的错误。
以下是可能的解决方法:
fixture.detectChanges()
来触发变更检测,并确保组件中的内容已经被渲染。it('should display the correct text', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.element-class').textContent).toContain('Expected Text');
});
it('should display the correct text', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.element-class').textContent).toContain('Expected Text');
});
beforeEach(() => {
const element = document.createElement('div');
element.className = 'element-class';
element.textContent = 'Expected Text';
document.body.appendChild(element);
});
it('should display the correct text', () => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.element-class').textContent).toContain('Expected Text');
});
通过以上方法,您应该能够解决“TypeError: Cannot read property 'textContent' of null”错误,并在Karma上成功运行测试。