填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

找出你要測試多少程式碼

Find out how much code you're testing

CLI 可以執行單元測試並建立程式碼覆蓋率報告。程式碼覆蓋率報告會向你展示程式碼函式庫中可能無法透過單元測試進行正確測試的任意部位。

The CLI can run unit tests and create code coverage reports. Code coverage reports show you any parts of your code base that may not be properly tested by your unit tests.

對於本測試指南中描述的範例應用,參閱範例應用範例應用

For the sample app that the testing guides describe, see thesample appsample app.

要了解本測試指南中涉及的測試特性,請參閱teststests

For the tests features in the testing guides, seeteststests.

要產生覆蓋率報告,請在專案的根目錄下執行以下命令。

To generate a coverage report run the following command in the root of your project.

      
      ng test --no-watch --code-coverage
    

測試完成後,該命令會在專案中建立一個 /coverage 目錄。開啟 index.html 檔案,可以檢視帶有原始碼和程式碼覆蓋率值的報表。

When the tests are complete, the command creates a new /coverage folder in the project. Open the index.html file to see a report with your source code and code coverage values.

如果要在每次測試時都建立程式碼覆蓋率報告,可以在 CLI 配置檔案 angular.json 中設定以下選項:

If you want to create code-coverage reports every time you test, you can set the following option in the CLI configuration file, angular.json:

      
      "test": {
  "options": {
    "codeCoverage": true
  }
}
    

程式碼覆蓋的實施

Code coverage enforcement

程式碼覆蓋率可以讓你估算出你的程式碼測試了多少。如果你的團隊確定要設定單元測試的最小覆蓋率,可以使用 Angular CLI 來強制實施這個最低要求。

The code coverage percentages let you estimate how much of your code is tested. If your team decides on a set minimum amount to be unit tested, you can enforce this minimum with the Angular CLI.

例如,假設你希望程式碼函式庫的程式碼覆蓋率至少達到 80%。要啟用此功能,請開啟 Karma 測試平臺的配置檔案 karma.conf.js,並在 coverageReporter: 鍵下新增 check 屬性。

For example, suppose you want the code base to have a minimum of 80% code coverage. To enable this, open the Karma test platform configuration file, karma.conf.js, and add the check property in the coverageReporter: key.

      
      coverageReporter: {
  dir: require('path').join(__dirname, './coverage/<project-name>'),
  subdir: '.',
  reporters: [
    { type: 'html' },
    { type: 'text-summary' }
  ],
  check: {
    global: {
      statements: 80,
      branches: 80,
      functions: 80,
      lines: 80
    }
  }
}
    

check 屬性會讓該工具在專案中執行單元測試時強制要求至少 80%的程式碼覆蓋率。

The check property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.

你可以在此處找到關於其它覆蓋率配置項的更多資訊。

You can find more info about the different coverage configuration options here.