測試實用工具 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));