跳至主要內容

API

Angular 測試函式庫 重新匯出 DOM 測試函式庫 的所有內容以及 render 方法。

以下重新匯出已進行修補,使其更容易與 Angular 一起使用

  • fireEvent 上的事件會在事件觸發後自動調用變更偵測週期
  • findBy 查詢會在調用查詢函式之前自動調用變更偵測週期
  • waitFor 函式會在調用回呼函式之前自動調用變更偵測週期

render

使用 Angular 測試函式庫,可以透過元件的類型或使用範本兩種方式來呈現元件。

預設情況下,render 也會匯入 NoopAnimationsModule

Type

若要呈現元件,您需要將元件的類型傳遞給 render 方法。對於不使用應用程式其他部分(例如設計模組或服務)的元件,呈現元件可以像以下範例一樣簡單。

await render(AppComponent)

template

除了將元件的類型作為第一個引數傳遞之外,您也可以提供範本。這種做法是呈現指令所必需的,但也適用於元件,甚至可能更有用。指令(或元件)的類型必須接著加入 declarations 中。

指令範例:

await render('<div appSpoiler></div>', {
declarations: [SpoilerDirective],
})

元件範例:

await render(
'<app-component [value]="47" [otherValue]="anotherValue" (sendValue)="sendValue($event)"></app-component>',
{
declarations: [AppComponent],
componentProperties: {
anotherValue: 'valueOfAnotherProperty',
sendValue: jest.fn(),
},
},
)
export async function render<ComponentType>(
component: Type<ComponentType>,
renderOptions?: RenderComponentOptions<ComponentType>,
): Promise<RenderResult<ComponentType, ComponentType>>
export async function render<WrapperType = WrapperComponent>(
template: string,
renderOptions?: RenderTemplateOptions<WrapperType>,
): Promise<RenderResult<WrapperType>>

元件 RenderOptions

inputs

用於設定元件的 @Inputinput() 屬性的物件。

預設值{}

await render(AppComponent, {
inputs: {
counterValue: 10,
// explicitly define aliases using `aliasedInput`
...aliasedInput('someAlias', 'someValue'),
},
})

on

具有回呼的物件,用於訂閱元件的 EventEmittersObservables

預設值{}

// using a manual callback
const sendValue = (value) => { ... }
// using a (jest) spy
const sendValueSpy = jest.fn()

await render(AppComponent, {
on: {
send: (value) => sendValue(value),
send: sendValueSpy
}
})

declarations

呈現元件所需的元件、指令和管道的集合。例如,元件的巢狀元件。

如需更多資訊,請參閱 Angular 文件

預設值[]

範例:

await render(AppComponent, {
declarations: [CustomerDetailComponent, ButtonComponent],
})

deferBlockBehavior

設定延遲區塊行為。

如需更多資訊,請參閱 Angular 文件

預設值undefined(使用 DeferBlockBehavior.Manual,這與 Angular 預設的 DeferBlockBehavior.Playthrough 不同)

範例:

await render(AppComponent, {
deferBlockBehavior: DeferBlockBehavior.Playthrough,
})

deferBlockStates

設定元件中可延遲區塊的初始狀態。

如需更多資訊,請參閱 Angular 文件

預設值undefined(使用 Angular 預設值,即 DeferBlockState.Placeholder

範例:

await render(FixtureComponent, {
deferBlockStates: DeferBlockState.Loading,
})

componentProviders

透過相依性注入呈現元件所需的供應商集合。

這些將在元件層級提供。若要在模組層級注入相依性,請使用 providers

如需更多資訊,請參閱 Angular 文件

預設值[]

範例:

await render(AppComponent, {
componentProviders: [AppComponentService],
})

componentImports

用於覆寫獨立元件匯入的匯入集合。

預設值undefined

範例:

await render(AppComponent, {
componentImports: [MockChildComponent],
})

childComponentOverrides

用於覆寫的指定子元件供應商集合。

預設值undefined

範例:

await render(AppComponent, {
childComponentOverrides: [
{
component: ChildOfAppComponent,
providers: [{provide: ChildService, useValue: {hello: 'world'}}],
},
],
})

detectChangesOnRender

在元件呈現後調用 detectChanges

預設值true

範例:

await render(AppComponent, {detectChangesOnRender: false})

autoDetectChanges

自動偵測變更,就像「真實」執行元件一樣。例如,當事件發生時,執行變更偵測週期。

預設值true

範例:

await render(AppComponent, {
autoDetectChanges: false,
})

excludeComponentDeclaration

排除要自動新增為宣告的元件。當元件在匯入的模組中宣告時,例如使用 SCAM,則需要此設定。

預設值false

範例:

await render(AppComponent, {
imports: [AppModule], // a module that includes AppComponent
excludeComponentDeclaration: true,
})

imports

呈現元件所需的匯入集合,例如,共用模組。如果未將 BrowserAnimationsModule 加入集合中,則預設會新增 NoopAnimationsModule

如需更多資訊,請參閱 Angular 文件

預設值[NoopAnimationsModule]

範例:

await render(AppComponent, {
imports: [AppSharedModule, MaterialModule],
})

providers

透過相依性注入呈現元件所需的供應商集合。

這些將在模組層級提供。若要在元件層級注入相依性,請使用 componentProviders

如需更多資訊,請參閱 Angular 文件

預設值[]

範例:

await render(AppComponent, {
providers: [
CustomersService,
{
provide: MAX_CUSTOMERS_TOKEN,
useValue: 10,
},
],
})

queries

要繫結的查詢。除非合併,否則會覆寫 DOM 測試函式庫的預設設定。

預設值undefined

範例:

await render(AppComponent, {
queries: {...queries, ...customQueries},
})

routes

透過 RouterTestingModule.withRoutes 設定路由器服務的路由組態。如需更多資訊,請參閱 Angular 路由文件

預設值[]

範例:

await render(AppComponent, {
declarations: [ChildComponent],
routes: [
{
path: '',
children: [
{
path: 'child/:id',
component: ChildComponent,
},
],
},
],
})

schemas

呈現元件所需的結構描述集合。允許的值為 NO_ERRORS_SCHEMACUSTOM_ELEMENTS_SCHEMA

如需更多資訊,請參閱 Angular 文件

預設值[]

範例:

await render(AppComponent, {
schemas: [NO_ERRORS_SCHEMA],
})

removeAngularAttributes

從 fixture 中移除 Angular 屬性(ng-version 和 root-id)。

預設值false

範例:

await render(AppComponent, {
removeAngularAttributes: true,
})

componentInputs (已棄用)

用於設定元件的 @Input 屬性的物件。使用 setInput 來設定輸入屬性。如果元件屬性未以 @Input 屬性註釋,則會擲回例外狀況。

預設值{}

範例:

await render(AppComponent, {
componentInputs: {
counterValue: 10,
},
})

componentOutputs (已棄用)

用於設定元件的 @Output 屬性的物件。

預設值{}

範例:

await render(AppComponent, {
componentOutputs: {
clicked: (value) => { ... }
}
})

componentProperties (已棄用)

用於設定元件的 @Input@Output 屬性的物件。沒有像 inputson 一樣的細微控制。

預設值{}

範例:

await render(AppComponent, {
componentProperties: {
// an input
counterValue: 10,
// an output
send: (value) => { ... }
// a public property
name: 'Tim'
}
})

RenderResult

container

您呈現的 Angular 元件的包含 DOM 節點。這是一個常規 DOM 節點,因此您可以調用 container.querySelector 等來檢查子節點。

debug

以語法醒目提示方式列印出元件的 DOM。接受可選參數,以列印出特定 DOM 節點。

const {debug} = await render(AppComponent)

debug()

rerender

透過遵循 Angular 元件生命週期事件(即調用 ngOnChanges)來變更現有元件實例的輸入屬性。未定義的輸入屬性會被清除。

const {rerender} = await render(Counter, {
inputs: {count: 4, name: 'Sarah'},
})

expect(screen.getByTestId('count-value').textContent).toBe('4')
expect(screen.getByTestId('name-value').textContent).toBe('Sarah')

await rerender({
inputs: {count: 7},
})

// count is updated to 7
expect(screen.getByTestId('count-value').textContent).toBe('7')
// name is undefined because it's not provided in rerender
expect(screen.getByTestId('name-value').textContent).toBeUndefined()

使用 partialUpdate,只會更新新提供的屬性。未提供的其他輸入屬性不會被清除。

const {rerender} = await render(Counter, {
inputs: {count: 4, name: 'Sarah'},
})

expect(screen.getByTestId('count-value').textContent).toBe('4')
expect(screen.getByTestId('name-value').textContent).toBe('Sarah')

await rerender({inputs: {count: 7}, partialUpdate: true})

// count is updated to 7
expect(screen.getByTestId('count-value').textContent).toBe('7')
// name is still rendered as "Sarah" because of the partial update
expect(screen.getByTestId('name-value').textContent).toBe('Sarah')

detectChanges

觸發元件的變更偵測週期。

如需更多資訊,請參閱 Angular 文件

debugElement

元件的 Angular DebugElement

如需更多資訊,請參閱 Angular 文件

fixture

元件的 Angular ComponentFixture

如需更多資訊,請參閱 Angular 文件

const {fixture} = await render(AppComponent)

// componentInstance is typed as AppComponent
const componentInstance = fixture.componentInstance

🚨 如果您發現自己使用 fixture 來存取元件的內部值,則應重新考慮!這可能表示您正在測試實作細節。

接受 DOM 元素或路徑作為參數。如果傳遞元素,navigate 將會導覽至元素的 href 值。如果傳遞路徑,navigate 將會導覽至該路徑。

const { navigate } = await render(AppComponent, {
routes: [...]
})

await navigate(component.getByLabelText('To details'))
await navigate('details/3')

...queries

render 的最重要功能是,DOM 測試函式庫 中的查詢會自動傳回,其第一個引數已繫結至受測元件。

如需完整清單,請參閱 查詢

範例:

const {getByText, queryByLabelText} = await render(AppComponent)

screen.getByRole('heading', {
name: /api/i,
})
queryByLabelText(/First name/i')

renderDeferBlock

若要測試可延遲檢視,您可以使用 renderDeferBlockrenderDeferBlock 將會為特定的可延遲區塊設定所需的延遲狀態。可延遲檢視的預設值為 Placeholder,但您也可以在渲染元件時設定初始狀態。

const {renderDeferBlock} = await render(FixtureComponent, {
deferBlockStates: DeferBlockState.Loading,
})

expect(screen.getByText(/loading/i)).toBeInTheDocument()

await renderDeferBlock(DeferBlockState.Complete)
expect(screen.getByText(/completed/i)).toBeInTheDocument()