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

測試

Testing

測試你的 Angular 應用可以幫助你檢查此應用是否正常執行。

Testing your Angular application helps you check that your app is working as you expect.

先決條件

Prerequisites

在為 Angular 應用編寫測試之前,你應該對這些概念有一個基本的瞭解:

Before writing tests for your Angular app, you should have a basic understanding of the following concepts:

  • Angular 的基本原理

    Angular fundamentals

  • JavaScript

  • HTML

  • CSS

  • Angular CLI


本測試文件透過使用 Angular CLI 建立的範例應用,為對 Angular 應用進行單元測試和整合測試提供了技巧和方法。這個範例應用很像“英雄之旅”課程中的應用。

The testing documentation offers tips and techniques for unit and integration testing Angular applications through a sample application created with the Angular CLI. This sample application is much like the one in the Tour of Heroes tutorial.

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

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

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

For the tests features in the testing guides, seeteststests.

建立環境

Set up testing

Angular CLI 會下載並安裝試用 Jasmine 測試框架 測試 Angular 應用時所需的一切。

The Angular CLI downloads and installs everything you need to test an Angular application with the Jasmine test framework.

你使用 CLI 建立的專案是可以立即用於測試的。 執行 CLI 命令 ng test即可:

The project you create with the CLI is immediately ready to test. Just run the ng testCLI command:

      
      ng test
    

ng test 命令在監視模式下建構應用,並啟動 karma 測試執行器

The ng test command builds the app in watch mode, and launches the Karma test runner.

它的控制檯輸出一般是這樣的:

The console output looks a bit like this:

      
      10% building modules 1/1 modules 0 active
...INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
...INFO [launcher]: Launching browser Chrome ...
...INFO [launcher]: Starting browser Chrome
...INFO [Chrome ...]: Connected on socket ...
Chrome ...: Executed 3 of 3 SUCCESS (0.135 secs / 0.205 secs)
    

最後一行很重要。它表示 Karma 運行了三個測試,而且這些測試都通過了。

The last line of the log is the most important. It shows that Karma ran three tests that all passed.

它還會開啟 Chrome 瀏覽器並在“ Jasmine HTML 報告器”中顯示測試輸出,就像這樣:

A Chrome browser also opens and displays the test output in the "Jasmine HTML Reporter" like this.

大多數人都會覺得瀏覽器中的報告比控制檯中的日誌更容易閱讀。 你可以點選一行測試,來單獨重跑這個測試,或者點選一行描述資訊來重跑所選測試組(“測試套件”)中的那些測試。

Most people find this browser output easier to read than the console log. You can click on a test row to re-run just that test or click on a description to re-run the tests in the selected test group ("test suite").

同時,ng test 命令還會監聽這些變化。

Meanwhile, the ng test command is watching for changes.

要檢視它的實際效果,就對 app.component.ts 做一個小修改,並儲存它。 這些測試就會重新執行,瀏覽器也會重新整理,然後新的測試結果就出現了。

To see this in action, make a small change to app.component.ts and save. The tests run again, the browser refreshes, and the new test results appear.

配置

Configuration

CLI 會為你產生 Jasmine 和 Karma 的配置檔案。

The CLI takes care of Jasmine and Karma configuration for you.

不過你也可以透過編輯 src/ 目錄下的 karma.conf.jstest.ts 檔案來微調很多選項。

You can fine-tune many options by editing the karma.conf.js in the root folder of the project and the test.ts files in the src/ folder.

karma.conf.js 檔案是 karma 配置檔案的一部分。 CLI 會基於 angular.json 檔案中指定的專案結構和 karma.conf.js 檔案,來在記憶體中構建出完整的執行時配置。

The karma.conf.js file is a partial Karma configuration file. The CLI constructs the full runtime configuration in memory, based on application structure specified in the angular.json file, supplemented by karma.conf.js.

要進一步瞭解 Jasmine 和 Karma 的配置項,請搜尋網路。

Search the web for more details about Jasmine and Karma configuration.

其他測試框架

Other test frameworks

你還可以使用其它的測試函式庫和測試執行器來對 Angular 應用進行單元測試。 每個函式庫和執行器都有自己特有的安裝過程、配置項和語法。

You can also unit test an Angular app with other testing libraries and test runners. Each library and runner has its own distinctive installation procedures, configuration, and syntax.

要了解更多,請搜尋網路。

Search the web to learn more.

測試檔名及其位置

Test file name and location

檢視 src/app 資料夾。

Look inside the src/app folder.

CLI 為 AppComponent 生成了一個名叫 app.component.spec.ts 的測試檔案。

The CLI generated a test file for the AppComponent named app.component.spec.ts.

測試檔案的副檔名必須是 .spec.ts,這樣工具才能識別出它是一個測試檔案,也叫規約(spec)檔案。

The test file extension must be .spec.tsso that tooling can identify it as a file with tests (AKA, a spec file).

app.component.tsapp.component.spec.ts 檔案位於同一個資料夾中,而且相鄰。 其根檔名部分(app.component)都是一樣的。

The app.component.ts and app.component.spec.ts files are siblings in the same folder. The root file names (app.component) are the same for both files.

請在你的專案中對任意型別的測試檔案都堅持這兩條約定。

Adopt these two conventions in your own projects for every kind of test file.

把測試規約(spec)檔案放在它要測試的檔案旁邊

Place your spec file next to the file it tests

最好把單元測試規約檔案放到與它們測試的應用原始碼檔案相同的資料夾中:

It's a good idea to put unit test spec files in the same folder as the application source code files that they test:

  • 這些測試很容易找到。

    Such tests are easy to find.

  • 你一眼就能看到應用中是否缺少一些測試。

    You see at a glance if a part of your application lacks tests.

  • 臨近的測試可以揭示一個部件會如何在上下文中工作。

    Nearby tests can reveal how a part works in context.

  • 當移動原始碼時(在所難免),你不會忘了同時移動測試。

    When you move the source (inevitable), you remember to move the test.

  • 當重新命名原始檔時(在所難免),你不會忘了重新命名測試檔案。

    When you rename the source file (inevitable), you remember to rename the test file.

把 spec 檔案放到 test 目錄下

Place your spec files in a test folder

應用的整合測試規範可以測試跨資料夾和模組的多個部分之間的互動。它們並不屬於任何一個特定的部分,所以把它們放在任何一個檔案旁都很不自然。

Application integration specs can test the interactions of multiple parts spread across folders and modules. They don't really belong to any part in particular, so they don't have a natural home next to any one file.

最好在 tests 目錄下為它們建立一個合適的資料夾。

It's often better to create an appropriate folder for them in the tests directory.

當然,用來測試那些測試助手的規約也位於 test 目錄下,緊挨著相應的測試助手檔案。

Of course specs that test the test helpers belong in the test folder, next to their corresponding helper files.

建立持續整合環境

Set up continuous integration

避免專案出 BUG 的最佳方式之一,就是使用測試套件。但是很容易忘了一直執行它。 持續整合(CI)伺服器讓你可以配置專案的程式碼儲存庫,以便每次提交和收到 Pull Request 時就會執行你的測試。

One of the best ways to keep your project bug-free is through a test suite, but it's easy to forget to run tests all the time. Continuous integration (CI) servers let you set up your project repository so that your tests run on every commit and pull request.

已經有一些像 Circle CI 和 Travis CI 這樣的付費 CI 伺服器,你還可以使用 Jenkins 或其它軟體來搭建你自己的免費 CI 伺服器。 雖然 Circle CI 和 Travis CI 是收費服務,但是它們也會為開源專案提供免費服務。 你可以在 GitHub 上建立公開專案,並免費享受這些服務。 當你為 Angular 儲存庫貢獻程式碼時,就會自動用 Circle CI 和 Travis CI 執行整個測試套件。

There are paid CI services like Circle CI and Travis CI, and you can also host your own for free using Jenkins and others. Although Circle CI and Travis CI are paid services, they are provided free for open source projects. You can create a public project on GitHub and add these services without paying. Contributions to the Angular repo are automatically run through a whole suite of Circle CI tests.

本文件解釋瞭如何配置你的專案,來執行 Circle CI 和 Travis CI,以及如何修改你的測試配置,以便能在這兩個環境下用 Chrome 瀏覽器來執行測試。

This article explains how to configure your project to run Circle CI and Travis CI, and also update your test configuration to be able to run tests in the Chrome browser in either environment.

為 Circle CI 配置專案

Configure project for Circle CI

步驟一:在專案的根目錄下建立一個名叫 .circleci 的目錄。

Step 1: Create a folder called .circleci at the project root.

步驟二:在這個新建的目錄下,建立一個名為 config.yml 的檔案,內容如下:

Step 2: In the new folder, create a file called config.yml with the following content:

      
      version: 2
jobs:
  build:
    working_directory: ~/my-project
    docker:
      - image: circleci/node:10-browsers
    steps:
      - checkout
      - restore_cache:
          key: my-project-{{ .Branch }}-{{ checksum "package-lock.json" }}
      - run: npm install
      - save_cache:
          key: my-project-{{ .Branch }}-{{ checksum "package-lock.json" }}
          paths:
            - "node_modules"
      - run: npm run test -- --no-watch --no-progress --browsers=ChromeHeadlessCI
    

該配置會快取 node_modules/ 並使用 npm run來執行 CLI 命令,因為 @angular/cli 並沒有裝到全域性。 要把引數傳給 npm 指令碼,這個單獨的雙中線(--)是必須的。

This configuration caches node_modules/ and uses npm runto run CLI commands, because @angular/cli is not installed globally. The double dash (--) is needed to pass arguments into the npm script.

步驟三:提交你的修改,並把它們推送到你的程式碼儲存庫中。

Step 3: Commit your changes and push them to your repository.

步驟四:註冊 Circle CI,並新增你的專案。你的專案將會開始建構。

Step 4: Sign up for Circle CI and add your project. Your project should start building.

為 Travis CI 配置專案

Configure project for Travis CI

步驟一:在專案根目錄下建立一個名叫 .travis.yml 的檔案,內容如下:

Step 1: Create a file called .travis.yml at the project root, with the following content:

      
      language: node_js
node_js:
  - "10"
addons:
  chrome: stable

cache:
  directories:
     - ./node_modules

install:
  - npm install

script:
  - npm run test -- --no-watch --no-progress --browsers=ChromeHeadlessCI
    

它做的事情和 Circle CI 的配置檔案一樣,只是 Travis 不用 Chrome,而是用 Chromium 代替。

This does the same things as the CircleCI configuration, except that Travis doesn't come with Chrome, so use Chromium instead.

步驟二:提交你的更改,並把它們推送到你的程式碼儲存庫。

Step 2: Commit your changes and push them to your repository.

步驟三:註冊 Travis CI新增你的專案。 你需要推送一個新的提交,以觸發建構。

Step 3: Sign up for Travis CI and add your project. You'll need to push a new commit to trigger a build.

為 GitLab CI 配置專案

Configure project for GitLab CI

步驟 1:在專案根目錄下建立一個名為 .gitlab-ci.yml 的檔案,內容如下:

Step 1: Create a file called .gitlab-ci.yml at the project root, with the following content:

      
      image: node:14.15-stretch
variables:
  FF_USE_FASTZIP: "true"

cache:
  untracked: true
  policy: push
  key: ${CI_COMMIT_SHORT_SHA}
  paths:
    - node_modules/

.pull_cached_node_modules:
  cache:
    untracked: true
    key: ${CI_COMMIT_SHORT_SHA}
    policy: pull

stages:
  - setup
  - test

install:
  stage: setup
  script:
    - npm ci

test:
  stage: test
  extends: .pull_cached_node_modules
  before_script:
    - apt-get update
    - wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
    - apt install -y ./google-chrome*.deb;
    - export CHROME_BIN=/usr/bin/google-chrome
  script:
    - npm run test -- --no-watch --no-progress --browsers=ChromeHeadlessCI
    

這種配置會 在 install 作業下快取 node_modules/,並在 test 作業中重新使用快取的 node_modules/

This configuration caches node_modules/ in the install job and re-uses the cached node_modules/ in the test job.

步驟 2:註冊 GitLab CI新增你的專案。你需要推送新的提交以觸發建構。

Step 2: Sign up for GitLab CI and add your project. You'll need to push a new commit to trigger a build.

步驟 3:提交你的更改並將其推送到你的程式碼儲存庫。

Step 3: Commit your changes and push them to your repository.

為 GitHub Actions 配置專案

Configure project for GitHub Actions

步驟 1:在專案的根目錄下建立一個名叫 .github/workflows 的資料夾

Step 1: Create a folder called .github/workflows at root of your project

步驟 2:在新資料夾中,建立一個名為 main.yml 的檔案,其內容如下:

Step 2: In the new folder, create a file called main.yml with the following content:

      
      name: CI Angular app through Github Actions
on: push
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 14.x
        uses: actions/setup-node@v1
        with:
          node-version: 14.x

      - name: Setup
        run: npm ci

      - name: Test
        run: |
          npm test -- --no-watch --no-progress --browsers=ChromeHeadlessCI
    

步驟 3:註冊 GitHub新增你的專案。你需要推送新的提交以觸發建構。

Step 3: Sign up for GitHub and add your project. You'll need to push a new commit to trigger a build.

步驟 4:提交你的更改並將其推送到你的程式碼儲存庫。

Step 4: Commit your changes and push them to your repository.

在 Chrome 中配置 CLI 以進行 CI 測試

Configure CLI for CI testing in Chrome

當你要用 CLI 命令 ng test 在自己的環境中執行 CI 測試時,你可能需要再調整一下配置,以執行 Chrome 瀏覽器測試。

While the CLI command ng test is generally running the CI tests in your environment, you might still need to adjust your configuration to run the Chrome browser tests.

這個配置檔案是給 Karma(直譯 "報應")測試執行器使用的,你必須改為不用沙箱的 Chrome 啟動方式。

There is a configuration file for the Karma JavaScript test runner, which you must adjust to start Chrome without sandboxing.

這個例子中我們將使用無頭 Chrome

We'll be using Headless Chrome in these examples.

  • 在 Karma 配置檔案 karma.conf.js 中,瀏覽器的緊下方,新增自訂的啟動器,名叫 ChromeNoSandbox。

    In the Karma configuration file, karma.conf.js, add a custom launcher called ChromeHeadlessCI below browsers:

      
      browsers: ['ChromeHeadlessCI'],
customLaunchers: {
  ChromeHeadlessCI: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox']
  }
},
    

現在你可以執行下列帶有 --no-sandbox 標誌的命令了:

Now you can run the following command to use the --no-sandbox flag:

      
      ng test --no-watch --no-progress --browsers=ChromeHeadlessCI
    

注意:目前,如果你正執行在 Windows 中,還要包含 --disable-gpu 標誌。參閱 crbug.com/737678

Note: Right now, you'll also want to include the --disable-gpu flag if you're running on Windows. See crbug.com/737678.

關於測試的更多資訊

More info on testing

當你設定準備好測試環境之後,可能會發現以下測試指南很有用。

After you've set up your app for testing, you may find the following testing guides useful.