由于动画中的 query() 调用,角度单元测试失败

lam*_*mbk 4 unit-testing jasmine angular

我有一个条目组件,其中包含登录表单和注册表单(每个组件都是自己的组件)。条目组件包含一个变量,说明是否显示登录组件或注册组件,并且可以使用模板中的元素进行切换。

切换此变量时,包装子组件的容器会随着登录 => 注册的变化而产生动画(反之亦然)。

当我单击此元素切换到单元测试中的注册表单时,测试失败,因为我需要fixture.detectChanges()在单击切换后调用才能与注册表单实例交互。此调用会fixture.detectChanges()导致以下错误。

Error: Unable to process animations due to the following failed trigger transitions @entryModeTransition has failed due to: 

- `query("app-login-form > form")` returned zero elements. (Use `query("app-login-form > form", { optional: true })` if you wish to allow this.)
Run Code Online (Sandbox Code Playgroud)

fixture.detectChanges()beforeEach() 块中还有一个调用。

我已确保将其包含NoopAnimationsModule在测试设置中,但这似乎并不能阻止动画触发(我认为NoopAnimationsModule会这样做)。

我可以简单地将{ optional: true }选项添加到query()动画定义中的调用中,但是我不喜欢在整个动画中添加此选项,因为它们只是为了防止测试失败。

如果相关,登录和注册表单组件将使用 进行模拟ng-mocks

有什么方法可以阻止动画在单元测试中运行?

lam*_*mbk 5

如果其他人遇到这个问题,我最终通过在规范设置中构建组件时覆盖动画来解决这个问题。

这样我仍然可以像在现有测试中一样模拟子组件,并且也不需要调整动画定义。

通过将元选项设置为包含空触发器定义的数组来完成覆盖,animations该定义与导致错误的动画同名。

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [EntryComponent, MockComponents(LoginFormComponent, RegisterFormComponent)],
      imports: [NoopAnimationsModule, ...other imports omitted],
      providers: [...providers omitted]
    })
      .overrideComponent(EntryComponent, {
        set: {
          animations: [trigger('entryModeTransition', [])]
        }
      })
      .compileComponents();
  }));
Run Code Online (Sandbox Code Playgroud)

如果许多测试需要此解决方法,则甚至可以将空触发器的创建移至实用程序函数,这可以整理覆盖:

.overrideComponent(EntryComponent, {
  set: {
    animations: mockAnimations(['entryFormTransition, 'someOtherTransition'])
  }
})
Run Code Online (Sandbox Code Playgroud)