API
Angular テスティングライブラリ
は、DOM テスティングライブラリ
のすべてとrender
メソッドを再エクスポートします。
以下の再エクスポートは、Angular で使いやすくするためにパッチが適用されています。
fireEvent
のイベントは、イベントが発生した後、自動的に変更検出サイクルを呼び出します。findBy
クエリは、クエリが呼び出される前に、自動的に変更検出サイクルを呼び出します。waitFor
関数は、コールバック関数を呼び出す前に、自動的に変更検出サイクルを呼び出します。
render
Angular テスティングライブラリでは、コンポーネントの型またはテンプレートを使用して、2つの方法でコンポーネントをレンダリングできます。
デフォルトでは、
render
はNoopAnimationsModule
もインポートします。
型
コンポーネントをレンダリングするには、コンポーネントの型を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ドキュメントをご覧ください。
デフォルト : 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 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_SCHEMA
とCUSTOM_ELEMENTS_SCHEMA
です。
詳しくは、Angularドキュメントをご覧ください。
デフォルト : []
例:
await render(AppComponent, {
schemas: [NO_ERRORS_SCHEMA],
})
removeAngularAttributes
フィクスチャからAngular属性(ng-version、およびroot-id)を削除します。
デフォルト : false
例:
await render(AppComponent, {
removeAngularAttributes: true,
})
componentInputs
(非推奨)
componentInputs
コンポーネントの@Input
プロパティを設定するオブジェクト。setInput
を使用して入力プロパティを設定します。コンポーネントプロパティに@Input
属性の注釈が付けられていない場合、エラーをスローします。
デフォルト : {}
例:
await render(AppComponent, {
componentInputs: {
counterValue: 10,
},
})
componentOutputs
(非推奨)
componentOutputs
コンポーネントの@Output
プロパティを設定するオブジェクト。
デフォルト : {}
例:
await render(AppComponent, {
componentOutputs: {
clicked: (value) => { ... }
}
})
componentProperties
(非推奨)
componentProperties
コンポーネントの@Input
および@Output
プロパティを設定するオブジェクト。inputs
とon
ほどきめ細かい制御はできません。
デフォルト : {}
例:
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
を使用してコンポーネントの内部値にアクセスしていることに気付いた場合は、再検討する必要があります。これはおそらく、実装の詳細をテストしていることを意味します。
navigate
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()