Angular 组件Dom测试

本文主要探讨Angular组件的DOM测试,包括使用`createComponent()`创建组件实例,通过ComponentFixture进行交互,利用`nativeElement`访问原生元素,以及借助DebugElement和By.css()进行测试辅助。测试中,我们关注组件的渲染、用户交互响应以及与其他组件的集成。
摘要由CSDN通过智能技术生成

组件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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值