{@a top}
# Testing
# 测试
This guide offers tips and techniques for unit and integration testing Angular applications.
该指南提供了对 Angular 应用进行单元测试和集成测试的技巧和提示。
The guide presents tests of a sample application created with the [Angular CLI](cli). This sample application is much like the one created in the [_Tour of Heroes_ tutorial](tutorial).
The sample application and all tests in this guide are available for inspection and experimentation:
该指南中的测试针对的是一个很像[《英雄指南》教程](tutorial)的 [Angular CLI](cli) 范例应用。
这个范例应用及其所有测试都可以在下面的链接中进行查看和试用:
- Sample app范例应用
- Tests测试
## Setup
## 建立环境
The Angular CLI downloads and installs everything you need to test an Angular application with the [Jasmine test framework](https://jasmine.github.io/).
Angular CLI 会下载并安装试用 [Jasmine 测试框架](https://jasmine.github.io/) 测试 Angular 应用时所需的一切。
The project you create with the CLI is immediately ready to test.
Just run the [`ng test`](cli/test) CLI command:
你使用 CLI 创建的项目是可以立即用于测试的。
运行 CLI 命令 [`ng test`](cli/test) 即可:
ng test
The `ng test` command builds the app in _watch mode_,
and launches the [Karma test runner](https://karma-runner.github.io).
`ng test` 命令在*监视模式*下构建应用,并启动 [karma 测试运行器](https://karma-runner.github.io)。
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)
The last line of the log is the most important.
It shows that Karma ran three tests that all passed.
最后一行很重要。它表示 Karma 运行了三个测试,而且这些测试都通过了。
A chrome browser also opens and displays the test output in the "Jasmine HTML Reporter" like this.
它还会打开 Chrome 浏览器并在“ Jasmine HTML 报告器”中显示测试输出,就像这样:
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").
大多数人都会觉得浏览器中的报告比控制台中的日志更容易阅读。
你可以点击一行测试,来单独重跑这个测试,或者点击一行描述信息来重跑所选测试组(“测试套件”)中的那些测试。
Meanwhile, the `ng test` command is watching for changes.
同时,`ng test` 命令还会监听这些变化。
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.
要查看它的实际效果,就对 `app.component.ts` 做一个小修改,并保存它。
这些测试就会重新运行,浏览器也会刷新,然后新的测试结果就出现了。
#### Configuration
#### 配置
The CLI takes care of Jasmine and Karma configuration for you.
CLI 会为你生成 Jasmine 和 Karma 的配置文件。
You can fine-tune many options by editing the `karma.conf.js` and
the `test.ts` files in the `src/` folder.
不过你也可以通过编辑 `src/` 目录下的 `karma.conf.js` 和 `test.ts` 文件来微调很多选项。
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`.
`karma.conf.js` 文件是 karma 配置文件的一部分。
CLI 会基于 `angular.json` 文件中指定的项目结构和 `karma.conf.js` 文件,来在内存中构建出完整的运行时配置。
Search the web for more details about Jasmine and Karma configuration.
要进一步了解 Jasmine 和 Karma 的配置项,请搜索网络。
#### Other test frameworks
#### 其它测试框架
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.
你还可以使用其它的测试库和测试运行器来对 Angular 应用进行单元测试。
每个库和运行器都有自己特有的安装过程、配置项和语法。
Search the web to learn more.
要了解更多,请搜索网络。
#### Test file name and location
#### 测试文件名及其位置
Look inside the `src/app` folder.
查看 `src/app` 文件夹。
The CLI generated a test file for the `AppComponent` named `app.component.spec.ts`.
CLI 为 `AppComponent` 生成了一个名叫 `app.component.spec.ts` 的测试文件。
The test file extension **must be `.spec.ts`** so that tooling can identify it as a file with tests (AKA, a _spec_ file).
测试文件的扩展名**必须是 `.spec.ts`**,这样工具才能识别出它是一个测试文件,也叫规约(spec)文件。
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.
`app.component.ts` 和 `app.component.spec.ts` 文件位于同一个文件夹中,而且相邻。
其根文件名部分(`app.component`)都是一样的。
Adopt these two conventions in your own projects for _every kind_ of test file.
请在你的项目中对*任意类型*的测试文件都坚持这两条约定。
{@a ci}
## Set up continuous integration
## 建立持续集成环境
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.
避免项目出 BUG 的最佳方式之一,就是使用测试套件。但是很容易忘了一直运行它。
持续集成(CI)服务器让你可以配置项目的代码仓库,以便每次提交和收到 Pull Request 时就会运行你的测试。
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 这样的付费 CI 服务器,你还可以使用 Jenkins 或其它软件来搭建你自己的免费 CI 服务器。
虽然 Circle CI 和 Travis CI 是收费服务,但是它们也会为开源项目提供免费服务。
你可以在 GitHub 上创建公开项目,并免费享受这些服务。
当你为 Angular 仓库贡献代码时,就会自动用 Circle CI 和 Travis CI 运行整个测试套件。
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 和 Travis CI,以及如何修改你的测试配置,以便能在这两个环境下用 Chrome 浏览器来运行测试。
### Configure project for Circle CI
### 为 Circle CI 配置项目
Step 1: Create a folder called `.circleci` at the project root.
步骤一:在项目的根目录下创建一个名叫 `.circleci` 的目录。
Step 2: In the new folder, create a file called `config.yml` with the following content:
步骤二:在这个新建的目录下,创建一个名为 `config.yml` 的文件,内容如下:
```
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
- run: npm run e2e -- --protractor-config=e2e/protractor-ci.conf.js
```
This configuration caches `node_modules/` and uses [`npm run`](https://docs.npmjs.com/cli/run-script) to run CLI commands, because `@angular/cli` is not installed globally.
The double dash (`--`) is needed to pass arguments into the `npm` script.
该配置会缓存 `node_modules/` 并使用 [`npm run`](https://docs.npmjs.com/cli/run-script) 来运行 CLI 命令,因为 `@angular/cli` 并没有装到全局。
要把参数传给 `npm` 脚本,这个单独的双中线(`--`)是必须的。
Step 3: Commit your changes and push them to your repository.
步骤三:提交你的修改,并把它们推送到你的代码仓库中。
Step 4: [Sign up for Circle CI](https://circleci.com/docs/2.0/first-steps/) and [add your project](https://circleci.com/add-projects).
Your project should start building.
步骤四:[注册 Circle CI](https://circleci.com/docs/2.0/first-steps/),并[添加你的项目](https://circleci.com/add-projects)。你的项目将会开始构建。
* Learn more about Circle CI from [Circle CI documentation](https://circleci.com/docs/2.0/).
欲知详情,参见 [Circle CI 文档](https://circleci.com/docs/2.0/)。
### Configure project for Travis CI
### 为 Travis CI 配置项目
Step 1: Create a file called `.travis.yml` at the project root, with the following content:
步骤一:在项目根目录下创建一个名叫 `.travis.yml` 的文件,内容如下:
```
dist: trusty
sudo: false
language: node_js
node_js:
- "10"
addons:
apt:
sources:
- google-chrome
packages:
- google-chrome-stable
cache:
directories:
- ./node_modules
install:
- npm install
script:
- npm run test -- --no-watch --no-progress --browsers=ChromeHeadlessCI
- npm run e2e -- --protractor-config=e2e/protractor-ci.conf.js
```
This does the same things as the Circle CI configuration, except that Travis doesn't come with Chrome, so we use Chromium instead.
它做的事情和 Circle CI 的配置文件一样,只是 Travis 不用 Chrome,而是用 Chromium 代替。
Step 2: Commit your changes and push them to your repository.
步骤二:提交你的更改,并把它们推送到你的代码仓库。
Step 3: [Sign up for Travis CI](https://travis-ci.org/auth) and [add your project](https://travis-ci.org/profile).
You'll need to push a new commit to trigger a build.
步骤三:[注册 Travis CI](https://travis-ci.org/auth) 并[添加你的项目](https://travis-ci.org/profile)。
你需要推送一个新的提交,以触发构建。
* Learn more about Travis CI testing from [Travis CI documentation](https://docs.travis-ci.com/).
欲知详情,参见 [Travis CI 文档](https://docs.travis-ci.com/)。
### Configure CLI for CI testing in Chrome
### 为在 Chrome 中运行 CI 测试而配置 CLI
When the CLI commands `ng test` and `ng e2e` are generally running the CI tests in your environment, you might still need to adjust your configuration to run the Chrome browser tests.
当 CLI 命令 `ng test` 和 `ng e2e` 经常要在你的环境中运行 CI 测试时,你可能需要再调整一下配置,以运行 Chrome 浏览器测试。
There are configuration files for both the [Karma JavaScript test runner](https://karma-runner.github.io/latest/config/configuration-file.html)
and [Protractor](https://www.protractortest.org/#/api-overview) end-to-end testing tool,
which you must adjust to start Chrome without sandboxing.
有一些文件是给 [Karma(直译 "报应")](https://karma-runner.github.io/latest/config/configuration-file.html)测试运行器和 [Protractor(直译 "量角器")](https://www.protractortest.org/#/api-overview) 端到端测试运行器使用的,你必须改为不用沙箱的 Chrome 启动方式。
We'll be using [Headless Chrome](https://developers.google.com/web/updates/2017/04/headless-chrome#cli) in these examples.
这个例子中我们将使用[无头 Chrome](https://developers.google.com/web/updates/2017/04/headless-chrome#cli)。
* In the Karma configuration file, `karma.conf.js`, add a custom launcher called ChromeHeadlessCI below browsers:
在 Karma 配置文件 `karma.conf.js` 中,浏览器的紧下方,添加自定义的启动器,名叫 ChromeNoSandbox。
```
browsers: ['Chrome'],
customLaunchers: {
ChromeHeadlessCI: {
base: 'ChromeHeadless',
flags: ['--no-sandbox']
}
},
```
* In the root folder of your e2e tests project, create a new file named `protractor-ci.conf.js`. This new file extends the original `protractor.conf.js`.
在 e2e 测试项目的根目录下创建一个新文件 `protractor-ci.conf.js`,它扩展了原始的 `protractor.conf.js`:
```
const config = require('./protractor.conf').config;
config.capabilities = {
browserName: 'chrome',
chromeOptions: {
args: ['--headless', '--no-sandbox']
}
};
exports.config = config;
```
Now you can run the following commands to use the `--no-sandbox` flag:
现在你可以运行下列带有 `--no-sandbox` 标志的命令了:
ng test --no-watch --no-progress --browsers=ChromeHeadlessCI
ng e2e --protractor-config=e2e/protractor-ci.conf.js
**Note:** Right now, you'll also want to include the `--disable-gpu` flag if you're running on Windows. See [crbug.com/737678](https://crbug.com/737678).
**注意:**目前,如果你正运行在 Windows 中,还要包含 `--disable-gpu` 标志。参见 [crbug.com/737678](https://crbug.com/737678)。
{@a code-coverage}
## Enable code coverage reports
## 启用代码覆盖率报告
The CLI can run unit tests and create code coverage reports.
Code coverage reports show you any parts of our code base that may not be properly tested by your unit tests.
CLI 可以运行单元测试,并创建代码覆盖率报告。
代码覆盖率报告会向你展示代码库中有哪些可能未使用单元测试正常测试过的代码。
To generate a coverage report run the following command in the root of your project.
要生成覆盖率报告,请在项目的根目录下运行下列命令。
ng test --no-watch --code-coverage
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.
当测试完成时,该命令会在项目中创建一个新的 `/coverage` 目录。打开其 `index.html` 文件以查看带有源码和代码覆盖率值的报告。
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`:
如果你要在每次运行测试时都创建代码覆盖率报告,可以在 CLI 的配置文件 `angular.json` 中设置下列选项:
```
"test": {
"options": {
"codeCoverage": true
}
}
```
### Code coverage enforcement
### 代码覆盖率实施
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.
代码覆盖率能让你估计要测试的代码量。
如果你的开发组决定要设置单元测试的最小数量,就可以使用 Angular CLI 来守住这条底线。
For example, suppose you want the code base to have a minimum of 80% code coverage.
To enable this, open the [Karma](https://karma-runner.github.io) test platform configuration file, `karma.conf.js`, and add the following in the `coverageIstanbulReporter:` key.
比如,假设你希望代码有最少 80% 的代码覆盖率。
要启用它,请打开 [Karma](https://karma-runner.github.io) 测试平台的配置文件 `karma.conf.js`,并添加键 `coverageIstanbulReporter:` 如下。
```
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true,
thresholds: {
statements: 80,
lines: 80,
branches: 80,
functions: 80
}
}
```
The `thresholds` property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project.
这里的 `thresholds` 属性会让此工具在项目中运行单元测试时强制保证至少达到 80% 的测试覆盖率。
## Service Tests
## 对服务的测试
Services are often the easiest files to unit test.
Here are some synchronous and asynchronous unit tests of the `ValueService`
written without assistance from Angular testing utilities.
服务通常是单元测试中最简单的文件类型。
下面是一些针对 `ValueService` 的同步和异步单元测试,
编写它们时没有借助来自 Angular 测试工具集的任何协助。
{@a services-with-dependencies}
#### Services with dependencies
#### 带有依赖的服务
Services often depend on other services that Angular injects into the constructor.
In many cases, it's easy to create and _inject_ these dependencies by hand while
calling the service's constructor.
服务通常会依赖于一些 Angular 注入到其构造函数中的其它服务。
多数情况下,创建并在调用该服务的构造函数时,手工创建并注入这些依赖也是很容易的。
The `MasterService` is a simple example:
`MasterService` 就是一个简单的例子:
`MasterService` delegates its only method, `getValue`, to the injected `ValueService`.
`MasterService` 把它唯一的方法 `getValue` 委托给了注入进来的 `ValueService`。
Here are several ways to test it.
这里是几种测试它的方法。
The first test creates a `ValueService` with `new` and passes it to the `MasterService` constructor.
第一个测试使用 `new` 创建了 `ValueService`,然后把它传给了 `MasterService` 的构造函数。
However, injecting the real service rarely works well as most dependent services are difficult to create and control.
不过,对于大多数没这么容易创建和控制的依赖项来说,注入真实的服务很容易出问题。
Instead you can mock the dependency, use a dummy value, or create a
[spy](https://jasmine.github.io/2.0/introduction.html#section-Spies)
on the pertinent service method.
你可以改用模拟依赖的方式,你可以使用虚值或在相关的服务方法上创建一个[间谍(spy)](https://jasmine.github.io/2.0/introduction.html#section-Spies)。
Prefer spies as they are usually the easiest way to mock services.
优先使用间谍,因为它们通常是 Mock 服务时最简单的方式。
These standard testing techniques are great for unit testing services in isolation.
这些标准的测试技巧对于在隔离的环境下对服务进行单元测试非常重要。
However, you almost always inject services into application classes using Angular
dependency injection and you should have tests that reflect that usage pattern.
Angular testing utilities make it easy to investigate how injected services behave.
不过,你几乎迟早要用 Angular 的依赖注入机制来把服务注入到应用类中去,而且你应该已经有了这类测试。
Angular 的测试工具集可以让你轻松探查这种注入服务的工作方式。
#### Testing services with the _TestBed_
#### 使用 `TestBed`(测试机床)测试服务
Your app relies on Angular [dependency injection (DI)](guide/dependency-injection)
to create services.
When a service has a dependent service, DI finds or creates that dependent service.
And if that dependent service has its own dependencies, DI finds-or-creates them as well.
你的应用中会依赖 Angular 的[依赖注入 (DI)](guide/dependency-injection) 来创建服务。
当某个服务依赖另一个服务时,DI 就会找到或创建那个被依赖的服务。
如果那个被依赖的服务还有它自己的依赖,DI 也同样会找到或创建它们。
As service _consumer_, you don't worry about any of this.
You don't worry about the order of constructor arguments or how they're created.
作为服务的*消费方*,你不需要关心这些细节。
你不用关心构造函数中的参数顺序或如何创建它们。
As a service _tester_, you must at least think about the first level of service dependencies
but you _can_ let Angular DI do the service creation and deal with constructor argument order
when you use the `TestBed` testing utility to provide and create services.
但对于服务的*测试方*来说,你就至少要考虑服务的第一级依赖了。
不过你*可以*让 Angular DI 来负责服务的创建工作,但当你使用 `TestBed` 测试工具来提供和创建服务时,你仍然需要关心构造函数中的参数顺序。
{@a testbed}
#### Angular _TestBed_
The `TestBed` is the most important of the Angular testing utilities.
The `TestBed` creates a dynamically-constructed Angular _test_ module that emulates
an Angular [@NgModule](guide/ngmodules).
`TestBed` 是 Angular 测试工具中最重要的部分。
`TestBed` 会动态创建一个用来模拟 [@NgModule](guide/ngmodules) 的 Angular *测试*模块。
The `TestBed.configureTestingModule()` method takes a metadata object that can have most of the properties of an [@NgModule](guide/ngmodules).
`TestBed.configureTestingModule()` 方法接收一个元数据对象,其中具有 [@NgModule](guide/ngmodules) 中的绝大多数属性。
To test a service, you set the `providers` metadata property with an
array of the services that you'll test or mock.
要测试某个服务,就要在元数据的 `providers` 属性中指定一个将要进行测试或模拟的相关服务的数组。
Then inject it inside a test by calling `TestBed.inject()` with the service class as the argument.
然后通过调用 `TestBed.inject()`(参数为该服务类)把它注入到一个测试中。
**Note:** We used to have `TestBed.get()` instead of `TestBed.inject()`.
The `get` method wasn't type safe, it always returned `any`, and this is error prone.
We decided to migrate to a new function instead of updating the existing one given
the large scale use that would have an immense amount of breaking changes.
**注意:** 我们以前使用的是 `TestBed.get()`,而不是 `TestBed.inject()`。
`get` 方法不是类型安全的,它总是返回 `any`,这很容易出错。
考虑到大规模使用时会产生大量重大变更,我们决定将其迁移到新功能,而不是修改现有功能。
Or inside the `beforeEach()` if you prefer to inject the service as part of your setup.
或者,如果你更倾向于把该服务作为环境准备过程的一部分,就把它放在 `beforeEach()` 中。
When testing a service with a dependency, provide the mock in the `providers` array.
如果要测试一个带有依赖项的服务,那就把模拟对象放在 `providers` 数组中。
In the following example, the mock is a spy object.
在下面的例子中,模拟对象是一个间谍(spy)对象。
The test consumes that spy in the same way it did earlier.
该测试会像以前一样消费这个间谍对象。
{@a no-before-each}
#### Testing without _beforeEach()_
#### 不使用 `beforeEach` 进行测试
Most test suites in this guide call `beforeEach()` to set the preconditions for each `it()` test
and rely on the `TestBed` to create classes and inject services.
本指南中的大多数的测试套件都会调用 `beforeEach()` 来为每个 `it()` 测试准备前置条件,并依赖 `TestBed` 来创建类和注入服务。
There's another school of testing that never calls `beforeEach()` and prefers to create classes explicitly rather than use the `TestBed`.
另一些测试教程中也可能让你不要调用 `beforeEach()`,并且更倾向于显式创建类,而不要借助 `TestBed`。
Here's how you might rewrite one of the `MasterService` tests in that style.
下面的例子教你如何把 `MasterService` 的测试改写成那种风格。
Begin by putting re-usable, preparatory code in a _setup_ function instead of `beforeEach()`.
通过把可复用的准备代码放进一个单独的 `setup` 函数来代替 `beforeEach()`。
The `setup()` function returns an object literal
with the variables, such as `masterService`, that a test might reference.
You don't define _semi-global_ variables (e.g., `let masterService: MasterService`)
in the body of the `describe()`.
`setup()` 函数返回一个带有一些变量的对象字面量,比如 `masterService`,测试中可以引用它。
这样你就不用在 `describe()` 中定义一些*半全局性的*变量了(比如 `let masterService: MasterService` )。
Then each test invokes `setup()` in its first line, before continuing
with steps that manipulate the test subject and assert expectations.
然后,每个测试都会在第一行调用 `setup()`,然后再操纵被测主体以及对期望值进行断言。
Notice how the test uses
[_destructuring assignment_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
to extract the setup variables that it needs.
注意这些测试是如何使用 [解构赋值](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
来提取出所需变量的。
Many developers feel this approach is cleaner and more explicit than the
traditional `beforeEach()` style.
很多开发者觉得这种方式相比传统的 `beforeEach()` 风格更加干净、更加明确。
Although this testing guide follows the traditional style and
the default [CLI schematics](https://github.com/angular/angular-cli)
generate test files with `beforeEach()` and `TestBed`,
feel free to adopt _this alternative approach_ in your own projects.
虽然本章会遵循传统的风格,并且 [CLI](https://github.com/angular/devkit) 生成的默认测试文件也用的是
`beforeEach()` 和 `TestBed`,不过你可以在自己的项目中自由选择*这种可选方式*。
#### Testing HTTP services
#### 测试 HTTP 服务
Data services that make HTTP calls to remote servers typically inject and delegate
to the Angular [`HttpClient`](guide/http) service for XHR calls.
那些会向远端服务器发起 HTTP 调用的数据服务,通常会注入 Angular 的 [`HttpClient`](guide/http) 服务并委托它进行 XHR 调用。
You can test a data service with an injected `HttpClient` spy as you would
test any service with a dependency.
你可以像测试其它带依赖的服务那样,通过注入一个 `HttpClient` 间谍来测试这种数据服务。
The `HeroService` methods return `Observables`. You must
_subscribe_ to an observable to (a) cause it to execute and (b)
assert that the method succeeds or fails.
`HttpService` 中的方法会返回 `Observables`。*订阅*这些方法返回的可观察对象会让它开始执行,并且断言这些方法是成功了还是失败了。
The `subscribe()` method takes a success (`next`) and fail (`error`) callback.
Make sure you provide _both_ callbacks so that you capture errors.
Neglecting to do so produces an asynchronous uncaught observable error that
the test runner will likely attribute to a completely different test.
`subscribe()` 方法接受一个成功回调 (`next`) 和一个失败 (`error`) 回调。
你要确保同时提供了这两个回调,以便捕获错误。
如果忽略这些异步调用中未捕获的错误,测试运行器可能会得出截然不同的测试结论。
#### _HttpClientTestingModule_
Extended interactions between a data service and the `HttpClient` can be complex
and difficult to mock with spies.
如果将来 `HttpClient` 和数据服务之间有更多的交互,则可能会变得复杂,而且难以使用间谍进行模拟。
The `HttpClientTestingModule` can make these testing scenarios more manageable.
`HttpClientTestingModule` 可以让这些测试场景变得更加可控。
While the _code sample_ accompanying this guide demonstrates `HttpClientTestingModule`,
this page defers to the [Http guide](guide/http#testing-http-requests),
which covers testing with the `HttpClientTestingModule` in detail.
本章的*代码范例*要示范的是 `HttpClientTestingModule`,所以把部分内容移到了 [Http](guide/http#testing-http-requests) 一章,那里会详细讲解如何用 `HttpClientTestingModule` 进行测试。
## Component Test Basics
## 组件测试基础
A component, unlike all other parts of an Angular application,
combines an HTML template and a TypeScript class.
The component truly is the template and the class _working together_. To adequately test a component, you should test that they work together
as intended.
组件与 Angular 应用中的其它部分不同,它是由 HTML 模板和 TypeScript 类组成的。
组件其实是指模板加上与其合作的类。
要想对组件进行充分的测试,就要测试它们能否如预期的那样协作。
Such tests require creating the component's host element in the browser DOM,
as Angular does, and investigating the component class's interaction with
the DOM as described by its template.
这些测试需要在浏览器的 DOM 中创建组件的宿主元素(就像 Angular 所做的那样),然后检查组件类和 DOM 的交互是否如同它在模板中所描述的那样。
The Angular `TestBed` facilitates this kind of testing as you'll see in the sections below.
But in many cases, _testing the component class alone_, without DOM involvement,
can validate much of the component's behavior in an easier, more obvious way.
Angular 的 `TestBed` 为所有这些类型的测试提供了基础设施。
但是很多情况下,可以*单独测试组件类本身*而不必涉及 DOM,就已经可以用一种更加简单、清晰的方式来验证该组件的大多数行为了。
### Component class testing
### 单独测试组件类
Test a component class on its own as you would test a service class.
你可以像测试服务类一样测试组件类。
Consider this `LightswitchComponent` which toggles a light on and off
(represented by an on-screen message) when the user clicks the button.
考虑下面这个 `LightswitchComponent`,当用户点击按钮时,它会切换灯的开关状态(用屏幕上的消息展现出来)。
You might decide only to test that the `clicked()` method
toggles the light's _on/off_ state and sets the message appropriately.
你可能要测试 `clicked()` 方法能否正确切换灯的开关状态并设置合适的消息。
This component class has no dependencies. To test these types of classes, follow the same steps as you would for a service that has no dependencies:
该组件类没有依赖。要测试这些类,请遵循与测试那些无依赖服务相同的步骤:
1. Create a component using the new keyword.
使用 `new` 关键子创建一个组件。
2. Poke at its API.
测试其 API。
3. Assert expectations on its public state.
对其期望的公开状态进行断言。
Here is the `DashboardHeroComponent` from the _Tour of Heroes_ tutorial.
下面这段代码是来自《英雄指南》教程的 `DashboardHeroComponent`。
It appears within the template of a parent component,
which binds a _hero_ to the `@Input` property and
listens for an event raised through the _selected_ `@Output` property.
它渲染在父组件的模板中,那里把一个英雄绑定到了 `@Input` 属性上,并且通过 `@Output` 属性监听*选中英雄*时的事件。
You can test that the class code works without creating the `DashboardHeroComponent`
or its parent component.
你可以测试 `DashboardHeroComponent` 类,而不用完整创建它或其父组件。
When a component has dependencies, you may wish to use the `TestBed` to both
create the component and its dependencies.
当组件有依赖时,你可能要使用 `TestBed` 来同时创建该组件及其依赖。
The following `WelcomeComponent` depends on the `UserService` to know the name of the user to greet.
下面的 `WelcomeComponent` 依赖于 `UserService`,并通过它知道要打招呼的那位用户的名字。
You might start by creating a mock of the `UserService` that meets the minimum needs of this component.
你可能要先创建一个满足本组件最小需求的模拟版 `UserService`。
Then provide and inject _both the_ **component** _and the service_ in the `TestBed` configuration.
然后在 `TestBed` 的配置中提供并同时注入该**组件**和该**服务**。
Then exercise the component class, remembering to call the [lifecycle hook methods](guide/lifecycle-hooks) as Angular does when running the app.
然后使用这个组件类,别忘了像 Angular 运行本应用时那样调用它的[生命周期钩子方法](guide/lifecycle-hooks)。
### Component DOM testing
### 组件 DOM 的测试
Testing the component _class_ is as easy as testing a service.
测试组件*类*就像测试服务那样简单。
But a component is more than just its class.
A component interacts with the DOM and with other components.
The _class-only_ tests can tell you about class behavior.
They cannot tell you if the component is going to render properly,
respond to user input and gestures, or integrate with its parent and child components.
但组件不仅是这个类。
组件还要和 DOM 以及其它组件进行交互。
*只涉及类*的测试可以告诉你组件类的行为是否正常,
但是不能告诉你组件是否能正常渲染出来、响应用户的输入和查询或与它的父组件和子组件相集成。
None of the _class-only_ tests above can answer key questions about how the
components actually behave on screen.
上述*只涉及类*的测试没办法回答这些组件在屏幕上的行为之类的关键性问题:
- Is `Lightswitch.clicked()` bound to anything such that the user can invoke it?
`Lightswitch.clicked()` 是否真的绑定到了某些用户可以接触到的东西?
- Is the `Lightswitch.message` displayed?
`Lightswitch.message` 是否真的显示出来了?
- Can the user actually select the hero displayed by `DashboardHeroComponent`?
用户真的可以选择 `DashboardHeroComponent` 中显示的某个英雄吗?
- Is the hero name displayed as expected (i.e, in uppercase)?
英雄的名字是否如预期般显示出来了?(比如是否大写)
- Is the welcome message displayed by the template of `WelcomeComponent`?
`WelcomeComponent` 的模板是否显示了欢迎信息?
These may not be troubling questions for the simple components illustrated above.
But many components have complex interactions with the DOM elements
described in their templates, causing HTML to appear and disappear as
the component state changes.
这些问题对于上面这种简单的组件来说当然没有问题,
不过很多组件和它们模板中所描述的 DOM 元素之间会有复杂的交互,当组件的状态发生变化时,会导致一些 HTML 出现和消失。
To answer these kinds of questions, you have to create the DOM elements associated
with the components, you must examine the DOM to confirm that component state
displays properly at the appropriate times, and you must simulate user interaction
with the screen to determine whether those interactions cause the component to
behave as expected.
要回答这类问题,你就不得不创建那些与组件相关的 DOM 元素了,你必须检查 DOM 来确认组件的状态能在恰当的时机正常显示出来,并且必须通过屏幕来仿真用户的交互,以判断这些交互是否如预期的那般工作。
To write these kinds of test, you'll use additional features of the `TestBed`
as well as other testing helpers.
要想写这类测试,你就要用到 `TestBed` 的附加功能以及其它测试助手了。
#### CLI-generated tests
#### CLI 生成的测试
The CLI creates an initial test file for you by default when you ask it to
generate a new component.
当你用 CLI 生成新的组件时,它也会默认创建最初的测试文件。
For example, the following CLI command generates a `BannerComponent` in the `app/banner` folder (with inline template and styles):
比如,下列 CLI 命令会在 `app/banner` 文件夹中生成带有内联模板和内联样式的 `BannerComponent`:
ng generate component banner --inline-template --inline-style --module app
It also generates an initial test file for the component, `banner-external.component.spec.ts`, that looks like this:
它也会为组件生成最初的测试文件 `banner-external.component.spec.ts`,代码如下:
Because `compileComponents` is asynchronous, it uses
the [`async`](api/core/testing/async) utility
function imported from `@angular/core/testing`.
由于 `compileComponents` 是异步的,所以它要使用从 `@angular/core/testing` 中导入的工具函数 [`async`](api/core/testing/async)。
Please refer to the [async](#async) section for more details.
欲知详情,请参见 [async](#async) 部分。
#### Reduce the setup
#### 缩减环境准备代码
Only the last three lines of this file actually test the component
and all they do is assert that Angular can create the component.
这个文件中只有最后三行是真正测试组件的,它们用来断言 Angular 可以创建该组件。
The rest of the file is boilerplate setup code anticipating more advanced tests that _might_ become necessary if the component evolves into something substantial.
文件的其它部分都是为更高级的测试二准备的样板代码,当组件逐渐演变成更加实质性的东西时,它们才*可能*变成必备的。
You'll learn about these advanced test features below.
For now, you can radically reduce this test file to a more manageable size:
稍后你将学到这些高级的测试特性。
不过目前,你可以先把这些测试文件缩减成更加可控的大小,以便理解:
In this example, the metadata object passed to `TestBed.configureTestingModule`
simply declares `BannerComponent`, the component to test.
在这个例子中,传给 `TestBed.configureTestingModule` 的元数据对象中只声明了 `BannerComponent` —— 待测试的组件。
There's no need to declare or import anything else.
The default test module is pre-configured with
something like the `BrowserModule` from `@angular/platform-browser`.
不用声明或导入任何其它的东西。
默认的测试模块中已经预先配置好了一些东西,比如来自 `@angular/platform-browser` 的 `BrowserModule`。
Later you'll call `TestBed.configureTestingModule()` with
imports, providers, and more declarations to suit your testing needs.
Optional `override` methods can further fine-tune aspects of the configuration.
稍后你将会调用带有导入模块、服务提供者和更多可声明对象的 `TestBed.configureTestingModule()` 来满足测试所需。
将来还可以用可选的 `override` 方法对这些配置进行微调。
{@a create-component}
#### _createComponent()_
After configuring `TestBed`, you call its `createComponent()` method.
在配置好 `TestBed` 之后,你还可以调用它的 `createComponent()` 方法。
`TestBed.createComponent()` creates an instance of the `BannerComponent`,
adds a corresponding element to the test-runner DOM,
and returns a [`ComponentFixture`](#component-fixture).
`TestBed.createComponent()` 会创建一个 `BannerComponent` 的实例,把相应的元素添加到测试运行器的 DOM 中,然后返回一个 [`ComponentFixture`](#component-fixture) 对象。
Do not re-configure `TestBed` after calling `createComponent`.
在调用了 `createComponent` 之后就不能再重新配置 `TestBed` 了。
The `createComponent` method freezes the current `TestBed` definition,
closing it to further configuration.
`createComponent` 方法冻结了当前的 `TestBed` 定义,关闭它才能再进行后续配置。
You cannot call any more `TestBed` configuration methods, not `configureTestingModule()`,
nor `get()`, nor any of the `override...` methods.
If you try, `TestBed` throws an error.
你不能再调用任何 `TestBed` 的后续配置方法了,不能调 `configureTestingModule()`、不能调 `get()`,
也不能调用任何 `override...` 方法。
如果试图这么做,`TestBed` 就会抛出错误。
{@a component-fixture}
#### _ComponentFixture_
The [ComponentFixture](api/core/testing/ComponentFixture) is a test harness for interacting with the created component and its corresponding element.
[ComponentFixture](api/core/testing/ComponentFixture) 是一个测试挽具(就像马车缰绳),用来与所创建的组件及其 DOM 元素进行交互。
Access the component instance through the fixture and confirm it exists with a Jasmine expectation:
可以通过测试夹具(fixture)来访问该组件的实例,并用 Jasmine 的 `expect` 语句来确保其存在。
#### _beforeEach()_
You will add more tests as this component evolves.
Rather than duplicate the `TestBed` configuration for each test,
you refactor to pull the setup into a Jasmine `beforeEach()` and some supporting variables:
随着该组件的成长,你将会添加更多测试。
除了为每个测试都复制一份 `TestBed` 测试之外,你还可以把它们重构成 Jasmine 的 `beforeEach()` 中的准备语句以及一些支持性变量:
Now add a test that gets the component's element from `fixture.nativeElement` and
looks for the expected text.
现在,添加一个测试,用它从 `fixture.nativeElement` 中获取组件的元素,并查找是否存在所预期的文本内容。
{@a native-element}
#### _nativeElement_
The value of `ComponentFixture.nativeElement` has the `any` type.
Later you'll encounter the `DebugElement.nativeElement` and it too has the `any` type.
`ComponentFixture.nativeElement` 的值是 `any` 类型的。
稍后你将遇到的 `DebugElement.nativeElement` 也同样是 `any` 类型的。
Angular can't know at compile time what kind of HTML element the `nativeElement` is or
if it even is an HTML element.
The app might be running on a _non-browser platform_, such as the server or a
[Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API),
where the element may have a diminished API or not exist at all.
Angular 在编译期间没办法知道 `nativeElement` 是哪种 HTML 元素,甚至是否 HTML 元素(译注:比如可能是 SVG 元素)。
本应用还可能运行在*非浏览器平台上*,比如服务端渲染或 [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) 那里的元素可能只有一些缩水过的 API,甚至根本不存在。
The tests in this guide are designed to run in a browser so a
`nativeElement` value will always be an `HTMLElement` or
one of its derived classes.
本指南中的测试都是为运行在浏览器中而设计的,因此 `nativeElement` 的值一定会是 `HTMLElement` 或其派生类。
Knowing that it is an `HTMLElement` of some sort, you can use
the standard HTML `querySelector` to dive deeper into the element tree.
如果知道了它是某种 `HTMLElement`,你就可以用标准的 `querySelector` 在元素树中进行深挖了。
Here's another test that calls `HTMLElement.querySelector` to get the paragraph element and look for the banner text:
下面这个测试就会调用 `HTMLElement.querySelector` 来获取 `
` 元素,并在其中查找 Banner 文本:
{@a debug-element}
#### _DebugElement_
The Angular _fixture_ provides the component's element directly through the `fixture.nativeElement`.
Angular 的*夹具*可以通过 `fixture.nativeElement` 直接提供组件的元素。
This is actually a convenience method, implemented as `fixture.debugElement.nativeElement`.
它实际上是 `fixture.debugElement.nativeElement` 的一个便利方法。
There's a good reason for this circuitous path to the element.
这种访问元素的迂回方式有很好的理由。
The properties of the `nativeElement` depend upon the runtime environment.
You could be running these tests on a _non-browser_ platform that doesn't have a DOM or
whose DOM-emulation doesn't support the full `HTMLElement` API.
`nativeElement` 的属性取决于运行环境。
你可以在没有 DOM,或者其 DOM 模拟器无法支持全部 `HTMLElement` API 的平台上运行这些测试。
Angular relies on the `DebugElement` abstraction to work safely across _all supported platforms_.
Instead of creating an HTML element tree, Angular creates a `DebugElement` tree that wraps the _native elements_ for the runtime platform.
The `nativeElement` property unwraps the `DebugElement` and returns the platform-specific element object.
Angular 依赖于 `DebugElement` 这个抽象层,就可以安全的横跨*其支持的所有平台*。
Angular 不再创建 HTML 元素树,而是创建 `DebugElement` 树,其中包裹着相应运行平台上的*原生元素*。
`nativeElement` 属性会解开 `DebugElement`,并返回平台相关的元素对象。
Because the sample tests for this guide are designed to run only in a browser,
a `nativeElement` in these tests is always an `HTMLElement`
whose familiar methods and properties you can explore within a test.
因为本章的这些测试都设计为只运行在浏览器中,因此这些测试中的 `nativeElement` 总是 `HTMLElement`,
你可以在测试中使用那些熟悉的方法和属性进行浏览。
Here's the previous test, re-implemented with `fixture.debugElement.nativeElement`:
下面是对上一个测试改用 `fixture.debugElement.nativeElement` 进行的重新实现:
The `DebugElement` has other methods and properties that
are useful in tests, as you'll see elsewhere in this guide.
`DebugElement` 还有其它的方法和属性,它们在测试中也很有用,你将在本章的其它测试中看到它们。
You import the `DebugElement` symbol from the Angular core library.
你要从 Angular 核心库中导入 `DebugElement` 符号。
{@a by-css}
#### _By.css()_
Although the tests in this guide all run in the browser,
some apps might run on a different platform at least some of the time.
虽然本章中的测试都是运行在浏览器中的,不过有些应用可能会运行在其它平台上(至少一部分时间是这样)。
For example, the component might render first on the server as part of a strategy to make the application launch faster on poorly connected devices. The server-side renderer might not support the full HTML element API.
If it doesn't support `querySelector`, the previous test could fail.
比如,作为加快慢速网络设备上应用启动速度的一种策略,组件可能要先在服务器上渲染。服务端渲染可能无法支持完全的 HTML API。
如果它不支持 `querySelector`,那么前一个测试就会失败。
The `DebugElement` offers query methods that work for all supported platforms.
These query methods take a _predicate_ function that returns `true` when a node in the `DebugElement` tree matches the selection criteria.
`DebugElement` 提供了可以工作在所有受支持的平台上的查询方法。
这些查询方法接受一个谓词(predicate)函数,如果 `DebugElement` 树中的节点满足某个筛选条件,它就返回 `true`。
You create a _predicate_ with the help of a `By` class imported from a
library for the runtime platform. Here's the `By` import for the browser platform:
你可以在从库中导入的 `By` 类的帮助下为该运行平台创建谓词函数。下面这个 `By` 是从浏览器平台导入的:
The following example re-implements the previous test with
`DebugElement.query()` and the browser's `By.css` method.
下面这个例子使用 `DebugElement.query()` 和浏览器的 `By.css` 方法重新实现了前一个测试。
Some noteworthy observations:
值得注意的地方有:
- The `By.css()` static method selects `DebugElement` nodes
with a [standard CSS selector](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors 'CSS selectors').
`By.css()` 静态方法使用[标准 CSS 选择器](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors 'CSS selectors')选择了一些 `DebugElement` 节点。
- The query returns a `DebugElement` for the paragraph.
这次查询返回了 `
` 元素的一个 `DebugElement`。
- You must unwrap that result to get the paragraph element.
你必须解包此结果,以获取这个 `
` 元素。
When you're filtering by CSS selector and only testing properties of a browser's _native element_, the `By.css` approach may be overkill.
当你要通过 CSS 选择器过滤,并且只打算测试浏览器的*原生元素*的属性时,`By.css` 这种方法就有点多余了。
It's often easier and more clear to filter with a standard `HTMLElement` method
such as `querySelector()` or `querySelectorAll()`,
as you'll see in the next set of tests.
使用标准的 `HTMLElement` 方法,比如 `querySelector()` 或 `querySelectorAll()` 通常会更简单、更清晰。
你在下一组测试中就会体会到这一点。
## Component Test Scenarios
## 组件测试场景
The following sections, comprising most of this guide, explore common
component testing scenarios
下面这些部分构成了本指南的大部分内容,它们将探讨一些常见的组件测试场景。
### Component binding
### 组件绑定
The current `BannerComponent` presents static title text in the HTML template.
当前的 `BannerComponent` 在 HTML 模板中展示了静态标题内容。
After a few changes, the `BannerComponent` presents a dynamic title by binding to
the component's `title` property like this.
稍作修改之后,`BannerComponent` 也可以通过绑定到组件的 `title` 属性来展示动态标题。就像这样:
Simple as this is, you decide to add a test to confirm that component
actually displays the right content where you think it should.
很简单,你决定添加一个测试来确定这个组件真的像你预期的那样显示出了正确的内容。
#### Query for the _<h1>_
#### 查询 `
`
You'll write a sequence of tests that inspect the value of the `
` element
that wraps the _title_ property interpolation binding.
你将会写一系列测试来探查 `
` 元素的值,这个值包含在了带有 `title` 属性的插值绑定中。
You update the `beforeEach` to find that element with a standard HTML `querySelector`
and assign it to the `h1` variable.
你要修改 `beforeEach` 来使用标准的 HTML `querySelector` 来找到该元素,并把它赋值给 `h1` 变量。
{@a detect-changes}
#### _createComponent()_ does not bind data
#### `createComponent()` 函数不会绑定数据
For your first test you'd like to see that the screen displays the default `title`.
Your instinct is to write a test that immediately inspects the `
` like this:
你的第一个测试希望看到屏幕显示出了默认的 `title`。
你本能的写出如下测试来立即审查这个 `
` 元素:
_That test fails_ with the message:
但*测试失败了*,给出如下信息:
```javascript
expected '' to contain 'Test Tour of Heroes'.
```
Binding happens when Angular performs **change detection**.
因为绑定是在 Angular 执行**变更检测**时才发生的。
In production, change detection kicks in automatically
when Angular creates a component or the user enters a keystroke or
an asynchronous activity (e.g., AJAX) completes.
在产品阶段,当 Angular 创建组件、用户输入或者异步动作(比如 AJAX)完成时,会自动触发变更检测。
The `TestBed.createComponent` does _not_ trigger change detection; a fact confirmed in the revised test:
但 `TestBed.createComponent` *不能*触发变更检测。
可以在这个修改后的测试中确定这一点:
#### _detectChanges()_
You must tell the `TestBed` to perform data binding by calling `fixture.detectChanges()`.
Only then does the `
` have the expected title.
你必须通过调用 `fixture.detectChanges()` 来要求 `TestBed` 执行数据绑定。
然后 `
` 中才会具有所期望的标题。
Delayed change detection is intentional and useful.
It gives the tester an opportunity to inspect and change the state of
the component _before Angular initiates data binding and calls [lifecycle hooks](guide/lifecycle-hooks)_.
这种迟到的变更检测是故意设计的,而且很有用。
它给了测试者一个机会,*在 Angular 初始化数据绑定以及调用[生命周期钩子](guide/lifecycle-hooks)之前*探查并改变组件的状态。
Here's another test that changes the component's `title` property _before_ calling `fixture.detectChanges()`.
下面这个测试中,会在调用 `fixture.detectChanges()` *之前*修改组件的 `title` 属性。
{@a auto-detect-changes}
#### Automatic change detection
#### 自动变更检测
The `BannerComponent` tests frequently call `detectChanges`.
Some testers prefer that the Angular test environment run change detection automatically.
`BannerComponent` 的这些测试需要频繁调用 `detectChanges`。
有些测试者更喜欢让 Angular 测试环境自动运行变更检测。
That's possible by configuring the `TestBed` with the `ComponentFixtureAutoDetect` provider.
First import it from the testing utility library:
使用 `ComponentFixtureAutoDetect` 服务提供者来配置 `TestBed` 就可以做到这一点。
首先从测试工具库中导入它:
Then add it to the `providers` array of the testing module configuration:
然后把它添加到测试模块配置的 `providers` 数组中:
Here are three tests that illustrate how automatic change detection works.
这三个测试阐明了自动变更检测的工作原理。
The first test shows the benefit of automatic change detection.
第一个测试程序展示了自动检测的好处。
The second and third test reveal an important limitation.
The Angular testing environment does _not_ know that the test changed the component's `title`.
The `ComponentFixtureAutoDetect` service responds to _asynchronous activities_ such as promise resolution, timers, and DOM events.
But a direct, synchronous update of the component property is invisible.
The test must call `fixture.detectChanges()` manually to trigger another cycle of change detection.
第二和第三个测试程序显示了它重要的局限性。
Angular 测试环境**不会**知道测试程序改变了组件的 `title` 属性。
自动检测只对异步行为比如承诺的解析、计时器和 DOM 事件作出反应。
但是直接修改组件属性值的这种同步更新是不会触发**自动检测**的。
测试程序必须手动调用 `fixture.detectChange()`,来触发新一轮的变更检测周期。
Rather than wonder when the test fixture will or won't perform change detection,
the samples in this guide _always call_ `detectChanges()` _explicitly_.
There is no harm in calling `detectChanges()` more often than is strictly necessary.
相比于受测试工具有没有执行变更检测的困扰,本章中的例子更愿意**总是显式**调用 `detectChanges()`。
即使是在不需要的时候,频繁调用 `detectChanges()` 也没有任何坏处。
{@a dispatch-event}
#### Change an input value with _dispatchEvent()_
#### 使用 `dispatchEvent()` 修改输入值
To simulate user input, you can find the input element and set its `value` property.
要想模拟用户输入,你就要找到 `` 元素并设置它的 `value` 属性。
You will call `fixture.detectChanges()` to trigger Angular's change detection.
But there is an essential, intermediate step.
你要调用 `fixture.detectChanges()` 来触发 Angular 的变更检测。
但那只是一个基本的中间步骤。
Angular doesn't know that you set the input element's `value` property.
It won't read that property until you raise the element's `input` event by calling `dispatchEvent()`.
_Then_ you call `detectChanges()`.
Angular 不知道你设置了这个 `` 元素的 `value` 属性。
在你通过调用 `dispatchEvent()` 触发了该输入框的 `input` 事件之前,它不能读到那个值。
*调用完之后*你再调用 `detectChanges()`。
The following example demonstrates the proper sequence.
下面的例子演示了这个调用顺序。
### Component with external files
### 带有外部文件的组件
The `BannerComponent` above is defined with an _inline template_ and _inline css_, specified in the `@Component.template` and `@Component.styles` properties respectively.
上面的 `BannerComponent` 定义了一个*内联模板*和*内联 CSS*,分别是在 `@Component.template` 和 `@Component.styles` 属性中指定的。
Many components specify _external templates_ and _external css_ with the
`@Component.templateUrl` and `@Component.styleUrls` properties respectively,
as the following variant of `BannerComponent` does.
很多组件会分别用 `@Component.templateUrl` 和 `@Component.styleUrls` 属性来指定*外部模板*和*外部 CSS*,就像下面这个 `BannerComponent` 的变体中所做的一样:
This syntax tells the Angular compiler to read the external files during component compilation.
这个语法告诉 Angular 编译器在编译期间读取外部文件。
That's not a problem when you run the CLI `ng test` command because it
_compiles the app before running the tests_.
当你运行 CLI 的 `ng test` 命令的时候这毫无问题,因为它会*在运行测试之前先编译该应用*。
However, if you run the tests in a **non-CLI environment**,
tests of this component may fail.
For example, if you run the `BannerComponent` tests in a web coding environment such as [plunker](https://plnkr.co/), you'll see a message like this one:
不过,如果你在**非 CLI 环境下**运行这些测试,那么对该组件的测试就可能失败。
比如,如果你在像 [plunker](http://plnkr.co/) 这样的 Web 编程环境下运行 `BannerComponent` 的测试,就会看到如下信息:
Error: This test module uses the component BannerComponent
which is using a "templateUrl" or "styleUrls", but they were never compiled.
Please call "TestBed.compileComponents" before your test.
You get this test failure message when the runtime environment
compiles the source code _during the tests themselves_.
如果在*测试自身期间*,运行环境试图编译源码,就会出现这个测试错误信息。
To correct the problem, call `compileComponents()` as explained [below](#compile-components).
要解决这个问题,可以像[稍后](#compile-components)解释的那样调用一次 `compileComponents()`。
{@a component-with-dependency}
### Component with a dependency
### 带依赖的组件
Components often have service dependencies.
组件经常依赖其它服务。
The `WelcomeComponent` displays a welcome message to the logged in user.
It knows who the user is based on a property of the injected `UserService`:
`WelcomeComponent` 为登陆的用户显示一条欢迎信息。它从注入的 `UserService` 的属性得知用户的身份:
The `WelcomeComponent` has decision logic that interacts with the service, logic that makes this component worth testing.
Here's the testing module configuration for the spec file, `app/welcome/welcome.component.spec.ts`:
`WelcomeComponent` 带有与服务交互的决策逻辑,这些逻辑让该组件值得测试。
下面是 `app/welcome/welcome.component.spec.ts` 中的测试模块配置:
This time, in addition to declaring the _component-under-test_,
the configuration adds a `UserService` provider to the `providers` list.
But not the real `UserService`.
这次,在测试配置里不但声明了被测试的组件,而且在 `providers` 数组中添加了 `UserService` 依赖。但不是真实的 `UserService`。
{@a service-test-doubles}
#### Provide service test doubles
#### 提供服务的测试替身
A _component-under-test_ doesn't have to be injected with real services.
In fact, it is usually better if they are test doubles (stubs, fakes, spies, or mocks).
The purpose of the spec is to test the component, not the service,
and real services can be trouble.
被测试的组件不一定要注入真正的服务。实际上,服务的替身(Stub - 桩, Fake - 假冒品, Spy - 间谍或者 Mock - 模拟对象)通常会更加合适。
spec 的主要目的是测试组件,而不是服务。真实的服务可能连自身都有问题,不应该让它干扰对组件的测试。
Injecting the real `UserService` could be a nightmare.
The real service might ask the user for login credentials and
attempt to reach an authentication server.
These behaviors can be hard to intercept.
It is far easier and safer to create and register a test double in place of the real `UserService`.
注入真实的 `UserService` 有可能很麻烦。真实的服务可能询问用户登录凭据,也可能试图连接认证服务器。
可能很难处理这些行为。所以在真实的 `UserService` 的位置创建和注册 `UserService` 替身,会让测试更加容易和安全。
This particular test suite supplies a minimal mock of the `UserService` that satisfies the needs of the `WelcomeComponent` and its tests:
这个测试套件提供了 `UserService` 的一个最小化模拟对象,它能满足 `WelcomeComponent` 及其测试的需求:
{@a get-injected-service}
#### Get injected services
#### 获取注入的服务
The tests need access to the (stub) `UserService` injected into the `WelcomeComponent`.
测试程序需要访问被注入到 `WelcomeComponent` 中的 `UserService`(stub 类)。
Angular has a hierarchical injection system.
There can be injectors at multiple levels, from the root injector created by the `TestBed`
down through the component tree.
Angular 的注入系统是层次化的。
可以有很多层注入器,从根 `TestBed` 创建的注入器下来贯穿整个组件树。
The safest way to get the injected service, the way that **_always works_**,
is to **get it from the injector of the _component-under-test_**.
The component injector is a property of the fixture's `DebugElement`.
最安全并**总是有效**的获取注入服务的方法,是**从被测组件的注入器获取**。
组件注入器是 fixture 的 `DebugElement` 的属性之一。
{@a testbed-inject}
#### _TestBed.inject()_
You _may_ also be able to get the service from the root injector via `TestBed.inject()`.
This is easier to remember and less verbose.
But it only works when Angular injects the component with the service instance in the test's root injector.
你也可能通过 `TestBed.inject()` 来使用根注入器获取该服务。
这样更容易记住而且不那么啰嗦。
不过这只有当 Angular 组件需要的恰好是该测试的根注入器时才能正常工作。
In this test suite, the _only_ provider of `UserService` is the root testing module,
so it is safe to call `TestBed.inject()` as follows:
在这个测试套件中,`UserService` *唯一*的提供者就是根测试模块中的,因此调用 `TestBed.inject()` 就是安全的,代码如下:
For a use case in which `TestBed.inject()` does not work,
see the [_Override component providers_](#component-override) section that
explains when and why you must get the service from the component's injector instead.
对于那些不能用 `TestBed.inject()` 的测试用例,请参见[改写组件的提供者](#component-override)一节,那里解释了何时以及为何必须改从组件自身的注入器中获取服务。
{@a welcome-spec-setup}
#### Final setup and tests
#### 最终的准备及测试代码
Here's the complete `beforeEach()`, using `TestBed.inject()`:
下面是使用 `TestBed.inject()` 的完整的 `beforeEach()`:
And here are some tests:
下面是一些测试程序:
The first is a sanity test; it confirms that the stubbed `UserService` is called and working.
第一个测试程序是合法测试程序,它确认这个被模拟的 `UserService` 是否被调用和工作正常。
The second parameter to the Jasmine matcher (e.g., `'expected name'`) is an optional failure label.
If the expectation fails, Jasmine appends this label to the expectation failure message.
In a spec with multiple expectations, it can help clarify what went wrong and which expectation failed.
Jasmine 匹配器的第二个参数(比如 `'expected name'`)是一个可选的失败标签。
如果这个期待语句失败了,Jasmine 就会把这个标签追加显示到这条个期待语句的失败信息后面。
对于具有多个期待语句的规约,它可以帮助澄清到底什么出错了,以及哪个期待语句失败了。
The remaining tests confirm the logic of the component when the service returns different values.
The second test validates the effect of changing the user name.
The third test checks that the component displays the proper message when there is no logged-in user.
接下来的测试程序确认当服务返回不同的值时组件的逻辑是否工作正常。
第二个测试程序验证变换用户名字的效果。
第三个测试程序检查如果用户没有登录,组件是否显示正确消息。
{@a component-with-async-service}
### Component with async service
### 带有异步服务的组件
In this sample, the `AboutComponent` template hosts a `TwainComponent`.
The `TwainComponent` displays Mark Twain quotes.
在这个例子中,`AboutComponent` 的模板中还有一个 `TwainComponent`。
`TwainComponent` 用于显示引自马克·吐温的话。
Note that the value of the component's `quote` property passes through an `AsyncPipe`.
That means the property returns either a `Promise` or an `Observable`.
注意该组件的 `quote` 属性的值是通过 `AsyncPipe` 传进来的。
这意味着该属性或者返回 `Promise` 或者返回 `Observable`。
In this example, the `TwainComponent.getQuote()` method tells you that
the `quote` property returns an `Observable`.
在这个例子中,`TwainComponent.getQuote()` 方法告诉你 `quote` 方法返回的是 `Observable`。
The `TwainComponent` gets quotes from an injected `TwainService`.
The component starts the returned `Observable` with a placeholder value (`'...'`),
before the service can return its first quote.
`TwainComponent` 会从一个注入进来的 `TwainService` 来获取这些引文。
在服务返回第一条引文之前,该组件会先返回一个占位值(`'...'`)的 `Observable`。
The `catchError` intercepts service errors, prepares an error message,
and returns the placeholder value on the success channel.
It must wait a tick to set the `errorMessage`
in order to avoid updating that message twice in the same change detection cycle.
`catchError` 会拦截服务中的错误,准备错误信息,并在成功分支中返回占位值。
它必须等一拍(tick)才能设置 `errorMessage`,以免在同一个变更检测周期中两次修改这个消息而导致报错。
These are all features you'll want to test.
这就是你要测试的全部特性。
#### Testing with a spy
#### 使用间谍(Spy)进行测试
When testing a component, only the service's public API should matter.
In general, tests themselves should not make calls to remote servers.
They should emulate such calls. The setup in this `app/twain/twain.component.spec.ts` shows one way to do that:
当测试组件时,只应该关心服务的公共 API。
通常来说,测试不应该自己向远端服务器发起调用。
它们应该对这些调用进行仿真。`app/twain/twain.component.spec.ts` 中的准备代码展示了实现方式之一:
{@a service-spy}
Focus on the spy.
重点看这个间谍对象(spy)。
The spy is designed such that any call to `getQuote` receives an observable with a test quote.
Unlike the real `getQuote()` method, this spy bypasses the server
and returns a synchronous observable whose value is available immediately.
这个间谍的设计是:任何对 `getQuote` 的调用都会收到一个包含测试引文的可观察对象。
和真正的 `getQuote()` 方法不同,这个间谍跳过了服务器,直接返回了一个能立即解析出值的同步型可观察对象。
You can write many useful tests with this spy, even though its `Observable` is synchronous.
虽然它的 `Observable` 是同步的,不过你仍然可以使用这个间谍对象写出很多有用的测试。
{@a sync-tests}
#### Synchronous tests
#### 同步测试
A key advantage of a synchronous `Observable` is that
you can often turn asynchronous processes into synchronous tests.
同步 `Observable` 的一大优点就是你可以把那些异步的流程转换成同步测试。
Because the spy result returns synchronously, the `getQuote()` method updates
the message on screen immediately _after_
the first change detection cycle during which Angular calls `ngOnInit`.
因为间谍对象的结果是同步返回的,所以 `getQuote()` 方法会在 Angular 调用 `ngOnInit` 时触发的首次变更检测周期后立即修改屏幕上的消息。
You're not so lucky when testing the error path.
Although the service spy will return an error synchronously,
the component method calls `setTimeout()`.
The test must wait at least one full turn of the JavaScript engine before the
value becomes available. The test must become _asynchronous_.
但测试出错路径的时候就没这么幸运了。
虽然该服务的间谍也会返回一个同步的错误对象,但是组件的那个方法中调用了 `setTimeout()`。
这个测试必须至少等待 JavaScript 引擎的一个周期,那个值才会变成可用状态。因此这个测试变成了*异步的*。
{@a fake-async}
#### Async test with _fakeAsync()_
#### 使用 `fakeAsync()` 进行异步测试
To use `fakeAsync()` functionality, you must import `zone.js/dist/zone-testing` in your test setup file.
If you created your project with the Angular CLI, `zone-testing` is already imported in `src/test.ts`.
要使用 `fakeAsync()` 功能,你必须导入 `zone.js/dist/zone-testing`。
如果你是用 Angular CLI 创建的项目,那么 `src/test.ts` 中就已经导入好了 `zone-testing`。
The following test confirms the expected behavior when the service returns an `ErrorObservable`.
下列测试用于确保当服务返回 `ErrorObservable` 的时候也能有符合预期的行为。
Note that the `it()` function receives an argument of the following form.
注意这个 `it()` 函数接收了一个如下形式的参数。
```javascript
fakeAsync(() => { /* test body */ })
```
The `fakeAsync()` function enables a linear coding style by running the test body in a special `fakeAsync test zone`.
The test body appears to be synchronous.
There is no nested syntax (like a `Promise.then()`) to disrupt the flow of control.
`fakeAsync` 函数通过在一个特殊的*`fakeAsync` 测试区域(zone)*中运行测试体来启用线性代码风格。
测试体看上去是同步的。
这里没有嵌套式语法(如 `Promise.then()`)来打断控制流。
Limitation: The `fakeAsync()` function won't work if the test body makes an `XMLHttpRequest` (XHR) call.
XHR calls within a test are rare, but if you need to call XHR, see [`async()`](#async), below.
限制:如果测试体中发起了 `XMLHttpRequest`(XHR)调用,则 `fakeAsync()` 函数将不起作用。
测试中很少进行 XHR 调用,但是如果你需要调用 XHR,请参见下面的 [`async()`](#async) 部分。
{@a tick}
#### The _tick()_ function
#### `tick()` 函数
You do have to call [tick()](api/core/testing/tick) to advance the (virtual) clock.
你必须调用 `tick()` 函数来向前推动(虚拟)时钟。
Calling [tick()](api/core/testing/tick) simulates the passage of time until all pending asynchronous activities finish.
In this case, it waits for the error handler's `setTimeout()`.
调用 [`tick()`](api/core/testing/tick) 会模拟时光的流逝,直到所有未决的异步活动都结束为止。
在这个例子中,它会等待错误处理器中的 `setTimeout()`。
The [tick()](api/core/testing/tick) function accepts milliseconds and tickOptions as parameters, the millisecond (defaults to 0 if not provided) parameter represents how much the virtual clock advances. For example, if you have a `setTimeout(fn, 100)` in a `fakeAsync()` test, you need to use tick(100) to trigger the fn callback. The tickOptions is an optional parameter with a property called `processNewMacroTasksSynchronously` (defaults to true) represents whether to invoke new generated macro tasks when ticking.
[tick()](api/core/testing/tick) 函数接受一个毫秒值和一个 `tickOptions` 作为参数(如果没有提供毫秒值则默认为 0)。该参数表示虚拟时钟要前进多少。
比如,如果你的 `fakeAsync()` 测试中有一个 `setTimeout(fn, 100)` 函数,你就需要用 `tick(100)` 来触发它的 fn 回调。
`tickOptions` 是一个可选参数,具有名为 `processNewMacroTasksSynchronously`(默认为 `true`)的属性,表示是否要在滴答时调用新生成的宏任务。
The [tick()](api/core/testing/tick) function is one of the Angular testing utilities that you import with `TestBed`.
It's a companion to `fakeAsync()` and you can only call it within a `fakeAsync()` body.
[tick()](api/core/testing/tick) 函数是你从 `TestBed` 中导入的 Angular 测试实用工具之一。
它和 `fakeAsync()` 一同使用,并且你只能在 `fakeAsync()` 体中调用它。
#### tickOptions
In this example, we have a new macro task (nested setTimeout), by default, when we `tick`, the setTimeout `outside` and `nested` will both be triggered.
在这个例子中,我们有一个新的宏任务(嵌套的 setTimeout),默认情况下,当我们 `tick` 时,`setTimeout` 的 `outside` 和 `nested` 都会被触发。
And in some case, we don't want to trigger the new macro task when ticking, we can use `tick(milliseconds, {processNewMacroTasksSynchronously: false})` to not invoke new macro task.
某些情况下,我们在 ticking 时可能不希望触发新的宏任务,这时可以使用 `tick(milliseconds, {processNewMacroTasksSynchronously: false})` 来阻止。
#### Comparing dates inside fakeAsync()
#### 在 `fakeAsync()` 中比较日期(date)
`fakeAsync()` simulates passage of time, which allows you to calculate the difference between dates inside `fakeAsync()`.
`fakeAsync()` 可以模拟时光的流逝,它允许你在 `fakeAsync()` 中计算日期之间的差异。
#### jasmine.clock with fakeAsync()
#### `jasmine.clock` 与 `fakeAsync()`
Jasmine also provides a `clock` feature to mock dates. Angular automatically runs tests that are run after
`jasmine.clock().install()` is called inside a `fakeAsync()` method until `jasmine.clock().uninstall()` is called. `fakeAsync()` is not needed and throws an error if nested.
Jasmine 也提供了 `clock` 特性来模拟日期。在 `fakeAsync()` 方法内,Angular 会自动运行那些调用 `jasmine.clock().install()` 和调用 `jasmine.clock().uninstall()` 之间的测试。`fakeAsync()` 不是必须的,而且如果嵌套它会抛出错误。
By default, this feature is disabled. To enable it, set a global flag before importing `zone-testing`.
默认情况下,该特性是禁用的。要启用它,请在导入 `zone-testing` 之前设置一个全局标志。
If you use the Angular CLI, configure this flag in `src/test.ts`.
如果你使用 Angular CLI,请在 `src/test.ts` 中配置此标志。
```
(window as any)['__zone_symbol__fakeAsyncPatchLock'] = true;
import 'zone.js/dist/zone-testing';
```
#### Using the RxJS scheduler inside fakeAsync()
#### 在 `fakeAsync()` 内使用 RxJS 调度器(scheduler)
You can also use RxJS scheduler in `fakeAsync()` just like using `setTimeout()` or `setInterval()`, but you need to import `zone.js/dist/zone-patch-rxjs-fake-async` to patch RxJS scheduler.
你还可以在 `fakeAsync()` 中使用 RxJS 调度器,就像 `setTimeout()` 或 `setInterval()` 一样,但是你要导入 `zone.js/dist/zone-patch-rxjs-fake-async` 来 patch 掉 RxJS 的调度器。
#### Support more macroTasks
#### 支持更多宏任务(macroTasks)
By default, `fakeAsync()` supports the following macro tasks.
默认情况下,`fakeAsync()` 支持下列 `macroTasks`。
- `setTimeout`
- `setInterval`
- `requestAnimationFrame`
- `webkitRequestAnimationFrame`
- `mozRequestAnimationFrame`
If you run other macro tasks such as `HTMLCanvasElement.toBlob()`, an _"Unknown macroTask scheduled in fake async test"_ error will be thrown.
如果你运行其它 `macroTasks`(比如 `HTMLCanvasElement.toBlob()`)就会抛出一条 `Unknown macroTask scheduled in fake async test` 错误。
If you want to support such a case, you need to define the macro task you want to support in `beforeEach()`.
For example:
如果你要支持这种情况,就要在 `beforeEach()` 中定义你要支持的宏任务。比如:
Note that in order to make the `