基本測試指令
以下是在 Angular 專案中進行測試常用的指令,包括啟動測試、測試特定檔案、調整測試配置等:
啟動測試
ng test
啟動 Karma 測試執行器,在瀏覽器中運行所有測試
預設會監視檔案變更並自動重新執行測試
單次執行測試(不持續監視)
ng test --watch=false
執行測試後立即結束,不會監視檔案變更
適合 CI/CD 環境或只想快速執行一次測試
產生測試覆蓋率報告
ng test --code-coverage
生成覆蓋率報告,顯示測試覆蓋了哪些程式碼
報告會存放在專案根目錄下的
/coverage
資料夾中
選擇性測試
測試特定檔案
ng test --include=**/multiple-select.component.spec.ts
只執行指定的測試檔案
測試特定路徑下的所有測試
ng test --include=**/shared/**/*.spec.ts
執行特定目錄下的所有測試檔案
排除特定的測試
ng test --exclude=**/auth/**/*.spec.ts
執行除了特定目錄外的所有測試
測試配置調整
變更瀏覽器
ng test --browsers=Chrome,Firefox
可以在多個瀏覽器中同時執行測試
無頭模式測試(不開啟瀏覽器視窗)
ng test --browsers=ChromeHeadless
在無頭 Chrome 中執行測試,不會開啟瀏覽器視窗
適合 CI/CD 環境
指定測試配置檔
ng test --karma-config=karma.conf.js
使用自定義的 Karma 配置檔案
指定 Jasmine 內容資料夾
ng test --source-map=false
關閉原始碼映射,可以加快測試速度
測試除錯
使用異常檢測
ng test --source-map=true
啟用原始碼映射,便於測試除錯
在測試中開啟除錯模式
在執行 ng test
後,Karma 瀏覽器界面上方有一個 "Debug" 按鈕,點擊它後可以使用瀏覽器開發工具進行除錯。
調整測試輸出格式
使用進度報告器
ng test --progress=true
顯示測試執行的進度
設定報告格式
ng test --reporters=junit,kjhtml
變更測試結果的報告格式
可選格式包括:dots、progress、junit、karma-jasmine-html-reporter 等
建立測試檔案
為元件生成測試
ng generate component my-component --spec=true
建立元件時同時生成測試檔案(這是預設行為)
為服務生成測試
ng generate service my-service --spec=true
建立服務時同時生成測試檔案
只生成測試檔案
ng generate spec --name=my-component
為已有的元件生成測試檔案
其他實用指令
更新測試執行環境
ng update @angular/cli @angular/core
更新 Angular 核心套件,包括測試相關的套件
安裝測試相關依賴
npm install --save-dev @angular/platform-browser-dynamic @angular/compiler-cli @types/jasmine jasmine-core karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter
安裝或更新測試所需的依賴套件
執行 E2E 測試 (Angular 最新版本使用 Cypress、Playwright 或 Protractor)
ng e2e
執行端對端測試(如果已配置)
測試指令組合範例
CI/CD 專用的完整測試指令
ng test --watch=false --browsers=ChromeHeadless --code-coverage
執行所有測試,單次執行不監視,使用無頭瀏覽器,並生成覆蓋率報告
開發時快速測試特定元件
ng test --include=**/multiple-select.component.spec.ts
只測試您正在開發的特定元件
Last updated