在使用Angular、Jasmine和Karma进行测试执行时,出现了意外的合成属性@hoge的错误

首先

由于尝试使用Angular、Jasmine和Karma来执行包含动画的组件测试时遇到了一些困难,特此记录备忘。

前提 tí) : premise

测试的组件使用了@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', () => {
    ...
  });
});

通过在每个测试前导入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', () => {
    ...
  });
});
广告
将在 10 秒后关闭
bannerAds