组件Dom测试
组件不仅仅是一个类,它还会与 DOM 以及其它组件进行交互。我们要知道组件是否能正确渲染、是否响应用户输入和手势,或者是否集成到它的父组件和子组件中,我们需要借助TestBed
的其它特性和其它的测试辅助函数。
describe('BannerComponent (with beforeEach)', () => {
let component: BannerComponent; // 要测试的组件BannerComponent
let fixture: ComponentFixture<BannerComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
// 声明要测试的组件
declarations: [BannerComponent]
});
// TestBed.createComponent 创建BannerComponent组件实例,返回一个`ComponentFixture` 对象
fixture = TestBed.createComponent(BannerComponent);
// ComponentFixture.componentInstance 拿到 BannerComponent实例
component = fixture.componentInstance;
});
it('should create', () => {
// 断言组件被定义了
expect(component).toBeDefined();
});
// ComponentFixture.nativeElement 获取组件的元素,并查找预期的文本。
it('should contain "banner works!"', () => {
const bannerElement: HTMLElement = fixture.nativeElement;
expect(bannerElement.textContent).toContain('banner works!');
});
});
createComponent()
TestBed.createComponent()
会创建 BannerComponent 的实例,它把一个对应元素添加到了测试运行器的 DOM 中,并返回一个ComponentFixture
对象。
const fixture: ComponentFixture