测试实用工具 API
Testing Utility APIs
本页面描述了一些最有用的 Angular 测试特性。
This page describes the most useful Angular testing features.
Angular 测试实用工具包括 TestBed
、ComponentFixture
以及一些控制测试环境的函数。 TestBed 和 ComponentFixture 类是单独介绍的。
The Angular testing utilities include the TestBed
, the ComponentFixture
, and a handful of functions that control the test environment. The TestBed and ComponentFixture classes are covered separately.
下面是一些独立函数的摘要,以使用频率排序:
Here's a summary of the stand-alone functions, in order of likely utility:
函数 Function | 说明 Description |
---|---|
在一个特殊的 async 测试区域中运行测试( Runs the body of a test ( | |
在一个特殊的 fakeAsync 测试区域中运行测试( Runs the body of a test ( | |
通过在 fakeAsync 测试区域中刷新定时器和微任务(micro-task)队列来仿真时间的流逝以及异步活动的完成。 Simulates the passage of time and the completion of pending asynchronous activities by flushing both timer and micro-task queues within the fakeAsync test zone. 好奇和执着的读者可能会喜欢这篇长博客: "Tasks, microtasks, queues and schedules". The curious, dedicated reader might enjoy this lengthy blog post, "Tasks, microtasks, queues and schedules". 接受一个可选参数,它可以把虚拟时钟往前推进特定的微秒数。 清除调度到那个时间帧中的异步活动。 参阅前面的讨论。 Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe. See discussion above. | |
| 从当前的 Injects one or more services from the current |
当 When a 一般来讲,测试程序应该以无排队任务结束。 当待执行计时器任务存在时,调用 In general, a test should end with no queued tasks. When pending timer tasks are expected, call | |
当 When a 一般来说,测试应该等待微任务结束。 当待执行微任务存在时,调用 In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call | |
一个服务提供者令牌,用于开启自动变更检测。 A provider token for a service that turns on automatic change detection. | |
获取当前 Gets the current instance of the |
TestBed
类摘要
TestBed class summary
TestBed
类是 Angular 测试工具的主要类之一。它的 API 很庞大,可能有点过于复杂,直到你一点一点的探索它们。 阅读本章前面的部分,了解了基本的知识以后,再试着了解完整 API。
The TestBed
class is one of the principal Angular testing utilities. Its API is quite large and can be overwhelming until you've explored it, a little at a time. Read the early part of this guide first to get the basics before trying to absorb the full API.
传给 configureTestingModule
的模块定义是 @NgModule
元数据属性的子集。
The module definition passed to configureTestingModule
is a subset of the @NgModule
metadata properties.
type TestModuleMetadata = {
providers?: any[];
declarations?: any[];
imports?: any[];
schemas?: Array<SchemaMetadata | any[]>;
};
每一个重载方法接受一个 MetadataOverride<T>
,这里 T
是适合这个方法的元数据类型,也就是 @NgModule
、@Component
、@Directive
或者 @Pipe
的参数。
Each override method takes a MetadataOverride<T>
where T
is the kind of metadata appropriate to the method, that is, the parameter of an @NgModule
, @Component
, @Directive
, or @Pipe
.
type MetadataOverride<T> = {
add?: Partial<T>;
remove?: Partial<T>;
set?: Partial<T>;
};
TestBed
的 API 包含了一系列静态类方法,它们更新或者引用全局的 TestBed
实例。
The TestBed
API consists of static class methods that either update or reference a global instance of the TestBed
.
在内部,所有静态方法在 getTestBed()
函数返回的当前运行时间的 TestBed
实例上都有对应的方法。
Internally, all static methods cover methods of the current runtime TestBed
instance, which is also returned by the getTestBed()
function.
在 BeforeEach()
内调用 TestBed
方法,以确保在运行每个单独测试时,都有崭新的开始。
Call TestBed
methods within a beforeEach()
to ensure a fresh start before each individual test.
这里列出了最重要的静态方法,以使用频率排序:
Here are the most important static methods, in order of likely utility.
方法 Methods | 说明 Description |
---|---|
| 测试垫片( The testing shims ( 调用 Call |
| 在配置好测试模块之后,异步编译它。 如果测试模块中的任何一个组件具有 Compile the testing module asynchronously after you've finished configuring it. You must call this method if any of the testing module components have a 调用完 After calling |
| 基于当前 Create an instance of a component of type |
| 替换指定的 Replace metadata for the given |
| 替换指定组件类的元数据,该组件类可能嵌套在一个很深的内部模块中。 Replace metadata for the given component class, which could be nested deeply within an inner module. |
| 替换指定指令类的元数据,该指令可能嵌套在一个很深的内部模块中。 Replace metadata for the given directive class, which could be nested deeply within an inner module. |
| 替换指定管道类的元数据,该管道可能嵌套在一个很深的内部模块中。 Replace metadata for the given pipe class, which could be nested deeply within an inner module. |
| 从当前 Retrieve a service from the current The 如果该服务是可选的呢? What if the service is optional? The
调用了 After calling |
| 为整套测试的运行初始化测试环境。 Initialize the testing environment for the entire test run. 测试垫片( The testing shims ( 这个方法只能被调用一次。如果确实需要在测试程序运行期间改变这个默认设置,那么先调用 You may call this method exactly once. If you must change this default in the middle of your test run, call 指定 Angular 编译器工厂, Specify the Angular compiler factory, a |
| 重设初始测试环境,包括默认测试模块在内。 Reset the initial test environment, including the default testing module. |
少数 TestBed
实例方法没有对应的静态方法。它们很少被使用。
A few of the TestBed
instance methods are not covered by static TestBed
class methods. These are rarely needed.
ComponentFixture
类
The ComponentFixture
TestBed.createComponent<T>
会创建一个组件 T
的实例,并为该组件返回一个强类型的 ComponentFixture
。
The TestBed.createComponent<T>
creates an instance of the component T
and returns a strongly typed ComponentFixture
for that component.
ComponentFixture
的属性和方法提供了对组件、它的 DOM 和它的 Angular 环境方面的访问。
The ComponentFixture
properties and methods provide access to the component, its DOM representation, and aspects of its Angular environment.
ComponentFixture
的属性
ComponentFixture properties
下面是对测试最重要的属性,以使用频率排序:
Here are the most important properties for testers, in order of likely utility.
属性 Properties | 说明 Description |
---|---|
| 被 The instance of the component class created by |
| 与组件根元素关联的 The The |
| 组件的原生根 DOM 元素。 The native DOM element at the root of the component. |
| 组件的 The 在测试一个拥有 The |
ComponentFixture
的方法
ComponentFixture methods
fixture 方法使 Angular 对组件树执行某些任务。 在触发 Angular 行为来模拟的用户行为时,调用这些方法。
The fixture methods cause Angular to perform certain tasks on the component tree. Call these method to trigger Angular behavior in response to simulated user action.
下面是对测试最有用的方法。
Here are the most useful methods for testers.
方法 Methods | 说明 Description |
---|---|
| 为组件触发一轮变化检查。 Trigger a change detection cycle for the component. 调用它来初始化组件(它调用 Call it to initialize the component (it calls 之后,运行 Runs |
| 如果你希望这个夹具自动检测变更,就把这个设置为 Set this to 当自动检测打开时,测试 fixture 监听 zone 事件,并调用 When autodetect is 默认值是 The default is |
| 运行一次变更检测来确认没有待处理的变化。如果有未处理的变化,它将抛出一个错误。 Do a change detection run to make sure there are no pending changes. Throws an exceptions if there are. |
| 如果 fixture 当前是稳定的,则返回 If the fixture is currently stable, returns |
| 返回一个承诺,在 fixture 稳定时解析。 Returns a promise that resolves when the fixture is stable. 要想在完成了异步活动或异步变更检测之后再继续测试,可以对那个承诺对象进行挂钩。 参阅 前面。 To resume testing after completion of asynchronous activity or asynchronous change detection, hook that promise. See above. |
| 触发组件的销毁。 Trigger component destruction. |
DebugElement
DebugElement
提供了对组件的 DOM 的访问。
The DebugElement
provides crucial insights into the component's DOM representation.
fixture.debugElement
返回测试根组件的 DebugElement
,通过它你可以访问(查询)fixture 的整个元素和组件子树。
From the test root component's DebugElement
returned by fixture.debugElement
, you can walk (and query) the fixture's entire element and component subtrees.
下面是 DebugElement
最有用的成员,以使用频率排序。
Here are the most useful DebugElement
members for testers, in approximate order of utility:
成员 Member | 说明 Description |
---|---|
| 与浏览器中 DOM 元素对应(WebWorkers 时,值为 null)。 The corresponding DOM element in the browser (null for WebWorkers). |
调用 Calling | |
| 调用 Calling |
| 宿主依赖注入器。 比如,根元素的组件实例注入器。 The host dependency injector. For example, the root element's component instance injector. |
| 元素自己的组件实例(如果有)。 The element's own component instance, if it has one. |
| 为元素提供父级上下文的对象。 通常是控制该元素的祖级组件实例。 An object that provides parent context for this element. Often an ancestor component instance that governs this element. 当一个元素被 When an element is repeated within |
| The immediate |
| The |
| 元素的标签名字,如果它是一个元素的话。 The element tag name, if it is an element. |
| 如果在该元素的 Triggers the event by its name if there is a corresponding listener in the element's 如果事件缺乏监听器,或者有其它问题,考虑调用 If the event lacks a listener or there's some other problem, consider calling |
| 元素的 The callbacks attached to the component's |
| 组件注入器的查询令牌。 包括组件自己的令牌和组件的 This component's injector lookup tokens. Includes the component itself plus the tokens that the component lists in its |
| source 是在源组件模板中查询这个元素的处所。 Where to find this element in the source component template. |
| 与模板本地变量(比如 Dictionary of objects associated with template local variables (e.g. |
DebugElement.query(predicate)
和 DebugElement.queryAll(predicate)
方法接受一个条件方法, 它过滤源元素的子树,返回匹配的 DebugElement
。
The DebugElement.query(predicate)
and DebugElement.queryAll(predicate)
methods take a predicate that filters the source element's subtree for matching DebugElement
.
这个条件方法是任何接受一个 DebugElement
并返回真值的方法。 下面的例子查询所有拥有名为 content
的模块本地变量的所有 DebugElement
:
The predicate is any method that takes a DebugElement
and returns a truthy value. The following example finds all DebugElements
with a reference to a template local variable named "content":
// Filter for DebugElements with a #content reference
const contentRefs = el.queryAll( de => de.references.content);
Angular 的 By
类为常用条件方法提供了三个静态方法:
The Angular By
class has three static methods for common predicates:
By.all
- 返回所有元素By.all
- return all elements.By.css(selector)
- 返回符合 CSS 选择器的元素。By.css(selector)
- return elements with matching CSS selectors.By.directive(directive)
- 返回 Angular 能匹配一个指令类实例的所有元素。By.directive(directive)
- return elements that Angular matched to an instance of the directive class.
// Can find DebugElement either by css selector or by directive
const h2 = fixture.debugElement.query(By.css('h2'));
const directive = fixture.debugElement.query(By.directive(HighlightDirective));