Week 10 · Day 01 — 單元測試:環境與 TestBed
學習目標
- 認識 Angular 測試工具(Jasmine + Karma)
- 理解
TestBed的角色 - 建立元件測試骨架
重點
測試工具
- Jasmine:測試框架(describe / it / expect)
- Karma:測試執行器(開瀏覽器跑測試)
- 用 ng test 啟動、ng test --watch 監看
TestBed 是什麼 - 測試用的「迷你 Angular 模組」,用來建立元件與注入服務 - 模擬真實運行環境
元件測試骨架(來自 CLI)
// hello.component.spec.ts
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { HelloComponent } from './hello.component';
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();
});
});
結構
- describe:測試群組
- beforeEach:每個測試前的準備(建立 TestBed、元件)
- it:單一測試案例
- expect(...).toBe(...):斷言
實作
- 執行
ng test,看到預設測試通過 - 找到
hello.component.spec.ts,試著刪掉it裡斷言再執行 - 加一個新的
it測試
作業
- 執行
ng test確認能跑 - 說出 Jasmine 的 describe / it / expect 用途
- 解釋
TestBed.configureTestingModule的作用