Jasmin & Karma 簡介
單元測試的重要性和原則
單元測試是測試程序中最小單元(如函數、方法)的過程。其重要性在於:
- 確保代碼質量:及早發現問題和缺陷。
 - 促進設計:使代碼更加模塊化。
 - 便於維護:當代碼變更時,單元測試能快速指出問題。
 
單元測試應遵循的原則包括:
- 自動化:自動執行,減少手動檢查。
 - 獨立性:每個測試應獨立於其他測試。
 - 可重複性:在任何環境中都能得到相同結果。
 
Jasmine 測試框架介紹
Jasmine 是一種行為驅動開發(Behavior-Driven Development, BDD)的測試框架,廣泛用於 JavaScript 應用程序。它不依賴任何其他 JavaScript 框架,且不需要 DOM。
基本的 Jasmine 測試語法
describe 和 it
describe("A suite", () => {
    it("contains spec with an expectation", () => {
        expect(true).toBe(true);
    });
});
describe字串描述測試組。it字串描述具體測試案例。
expect
expect 是 Jasmine 中斷言(Assertion)的功能,用於指定期望的輸出。
設置和撕除
beforeEach 和 afterEach
describe("A suite", () => {
    beforeEach(() => {
        // 在每個 spec 前執行
    });
    afterEach(() => {
        // 在每個 spec 後執行
    });
    it("example test", () => {
        // 測試內容
    });
});
Mocks 和 Spies
- Mocks:創建一個假的實例,模擬真實實例的行為。
 - Spies:追踪函數的調用情況,如是否被調用、調用次數等。
 
異步測試
處理非同步操作,Jasmine 提供了 done 函數。
it("async test", (done) => {
    setTimeout(() => {
        expect(true).toBe(true);
        done();
    }, 1000);
});
Karma 測試運行器配置和使用
Karma 是一個專為測試設計的工具,能夠在多種真實瀏覽器中運行測試代碼。它與 Jasmine 測試框架結合使用,尤其在 Angular 項目中非常流行。
Karma 配置
Karma 的配置通常在一個名為 karma.conf.js 的檔案中。以下是一個基本的配置範例:
module.exports = function(config) {
    config.set({
        basePath: '',
        frameworks: ['jasmine', '@angular-devkit/build-angular'],
        browsers: ['Chrome'],
        singleRun: false,
        reporters: ['progress'],
        // 其他配置...
    });
};
這個配置指定了使用的框架(Jasmine 和 Angular),測試運行的瀏覽器(Chrome),以及其他一些運行選項。
啟動 Karma
要啟動 Karma 測試,可以在命令行中運行以下命令:
ng test
這個命令會啟動 Karma,並根據 karma.conf.js 的配置在瀏覽器中運行測試。
Angular 中的測試實例
在 Angular 中,測試組件(Components)和服務(Services)是最常見的實踐。
測試組件
測試 Angular 組件時,通常需要檢查以下幾點:
- 組件是否正確創建。
 - 組件模板是否正確渲染。
 - 組件的方法是否正確執行。
 
範例:
describe('AppComponent', () => {
    beforeEach(async () => {
        await TestBed.configureTestingModule({
            declarations: [AppComponent]
        }).compileComponents();
    });
    it('should create the app', () => {
        const fixture = TestBed.createComponent(AppComponent);
        const app = fixture.componentInstance;
        expect(app).toBeTruthy();
    });
    // 其他測試...
});
測試服務
測試服務通常涉及以下方面:
- 服務方法的正確性。
 - 與 HTTP 請求相關的行為(如果有)。
 
範例:
describe('MyService', () => {
    let service: MyService;
    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(MyService);
    });
    it('should be created', () => {
        expect(service).toBeTruthy();
    });
    // 其他測試...
});
這些測試示例提供了在 Angular 中使用 Karma 和 Jasmine 進行組件和服務測試的基礎方法。通过這些測試,可以確保 Angular 應用的穩定性和可靠性。