Week 10 · Day 02 — 元件單元測試

學習目標

  • 測試元件的屬性與方法
  • fixture.detectChanges() 更新畫面
  • 搭配 ng test 持續驗證

重點

測試元件邏輯

describe('HelloComponent', () => {
  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [HelloComponent]
    }).compileComponents();

    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

  it('should display message', () => {
    expect(component.message).toBe('Hello from Angular!');
  });

  it('should change message', () => {
    component.changeMessage();
    expect(component.message).toBe('Message changed!');
  });
});

fixture 的角色 - fixture.componentInstance:元件實例 - fixture.detectChanges():觸發變更偵測,讓模板更新 - fixture.debugElement:查詢 DOM

測試模板渲染

const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h2')?.textContent).toContain('Hello from Angular!');
- 先 detectChanges() 再讀 DOM

實作

  1. 為 HelloComponent 寫測試:create / display / change
  2. 加一個「模板是否渲染 message」的測試(用 nativeElement)
  3. 故意改壞方法讓測試紅(red),修好再變綠(green)

作業

  • 測試元件屬性與方法
  • nativeElement 驗證模板渲染
  • 體驗一次 red → green 流程