はじめに
Angular, Jasmine, Karmaでアニメーションを含むコンポーネントのテストを実行しようとしたときに少し詰まったのでメモしておく
前提
テスト対象となるコンポーネントは@angular/animations
を使用していた
また、app.module.tsでBrowserAnimationsModuleをインポート済みだった
テスト対象コンポーネント
import { Component } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations'
@Component({
selector: 'app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
animations: [
trigger('hoge', [
state('a', style({ height: '*', opacity: 1 })),
state('b', style({ height: '0', opacity: 0 })),
transition('a => b', [animate('1s')]),
transition('b => a', [animate('1s')]),
]),
],
})
export class AppComponent {
...
}
原因
テストファイル(app.component.spec.ts)でBrowserAnimationsModuleをインポートできていなかった
修正前
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
}).compileComponents();
});
it('hoge', () => {
...
});
});
beforeEachでBrowserAnimationsModuleをインポートすることで解決した
修正後
import { TestBed } from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // 追加
import { AppComponent } from './app.component';
describe('App', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
imports: [BrowserAnimationsModule], // 追加
}).compileComponents();
});
it('hoge', () => {
...
});
});