メインコンテンツにスキップ

API

Angular テスティングライブラリは、DOM テスティングライブラリのすべてとrenderメソッドを再エクスポートします。

以下の再エクスポートは、Angular で使いやすくするためにパッチが適用されています。

  • fireEventのイベントは、イベントが発生した後、自動的に変更検出サイクルを呼び出します。
  • findByクエリは、クエリが呼び出される前に、自動的に変更検出サイクルを呼び出します。
  • waitFor関数は、コールバック関数を呼び出す前に、自動的に変更検出サイクルを呼び出します。

render

Angular テスティングライブラリでは、コンポーネントの型またはテンプレートを使用して、2つの方法でコンポーネントをレンダリングできます。

デフォルトでは、renderNoopAnimationsModuleもインポートします。

コンポーネントをレンダリングするには、コンポーネントの型を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

コンポーネントの@Inputまたはinput()プロパティを設定するオブジェクト。

デフォルト : {}

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

on

コンポーネントのEventEmittersおよびObservablesを購読するためのコールバックを持つオブジェクト。

デフォルト : {}

// 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ドキュメントをご覧ください。

デフォルト : undefinedDeferBlockBehavior.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 Testing Libraryのデフォルトセットをオーバーライドします。

デフォルト : undefined

:

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

routes

RouterTestingModule.withRoutesを介してルーターサービスを設定するためのルート構成。詳しくは、Angular Routesドキュメントをご覧ください。

デフォルト : []

:

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

フィクスチャから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`

遅延可能なビューをテストするには、`renderDeferBlock`を使用できます。 `renderDeferBlock`は、特定の遅延可能ブロックに必要な遅延状態を設定します。遅延可能ビューのデフォルト値は`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()