Angular Component的DOM级别的单元测试方法

142 阅读1分钟

HTMLElement

<span [textContent] = "AText"></span>

export class AComponent {
	AText = 'Some'
}

Angular编译器在解析模板时,遇到简单DOM元素比如span,就去查找该元素是否定义在dom element schema registry, 从而知道它是HTMLElement子类,textContent是其中一个属性。

如果遇到组件或者指令,就去查看其装饰器@Component,@Directive的元数据@Input属性里是否有该绑定属性。

目标

you have to create the DOM elements associated with the components, you must examine the DOM to confirm that component state displays properly at the appropriate times, and you must simulate user interaction with the screen to determine whether those interactions cause the component to behave as expected.

一个例子:

describe('BannerComponent (with beforeEach)', () => {
  let component: BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({declarations: [BannerComponent]});
    fixture = TestBed.createComponent(BannerComponent);
    component = fixture.componentInstance;
  });

  it('should create', () => {
    expect(component).toBeDefined();
  });
});

it('should contain "banner works!"', () => {
  const bannerElement: HTMLElement = fixture.nativeElement;
  expect(bannerElement.textContent).toContain('banner works!');
});

如果是在浏览器环境下运行,可以使用常规的DOM操作API访问HTML元素:

it('should have <p> with "banner works!"', () => {
  const bannerElement: HTMLElement = fixture.nativeElement;
  const p = bannerElement.querySelector('p');
  expect(p.textContent).toEqual('banner works!');
});

在这里插入图片描述