带有旁观者日志的角度组件测试针对模拟的子组件“无法绑定到输入”警告

时间:2020-09-16 18:32:12

标签: angular testing ngmock angular-spectator spectator

在使用@ ngneat / spectator的Angular 9组件测试中,我遇到了模拟子组件的问题。模拟和传递模拟可以正常工作,但是会在日志中为输入抛出警告(即使它们有效)。

简化的组件如下:

@Component({
  selector: 'child',
  template: '<h2>{{someInput}}</h2>'
})
export class ChildComponent {
  @Input() someInput: string;
}

@Component({
  selector: 'parent',
  template: '<child [someInput]="inputVal"></child>'
})
export class ParentComponent {
  public inputVal = 'hello';
}

现在是观众测试

import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
import { MockComponent } from 'ng-mocks';
...

describe('ParentComponent', () => {
  let spectator: Spectator<ParentComponent>;
  let createComponent: SpectatorFactory<ParentComponent>;

  beforeEach(() => {
    createComponent = createComponentFactory({
      component: ParentComponent,
      declarations: [MockComponent(ChildComponent)]
    });

    spectator = createComponent();
  });

  describe('example', () => {
    it('should set the input', () => {
      expect(spectator.query(ChildComponent).someInput).toEqual('hello');
    });
  });

});

测试运行正常并通过。但是,日志会显示警告:

console.warn
    Can't bind to 'someInput' since it isn't a known property of 'child'.

有什么想法为什么要记录警告?

1 个答案:

答案 0 :(得分:1)

发现了我自己的问题-事实证明createComponentFactory()必须在beforeEach()之外被调用。

一旦我将其从beforeEach块中移出,模拟就开始按预期工作。