天天看點

Angular Component的DOM級别的單元測試方法

Angular Component的DOM級别的單元測試方法

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!');
});

      
Angular Component的DOM級别的單元測試方法
Angular Component的DOM級别的單元測試方法

繼續閱讀