使用Jasmine测试从viewChild调用另一个方法的方法

Har*_*wer 6 jasmine karma-jasmine angular

我有这个方法来验证组件,它正在调用另一个组件,就是它ViewChild.我正在this.ViewChildComponent.someMethod();尝试测试的组件中使用组件.我试着用spyOn(viewChildComponent, 'someMethod').and.returnValue(true).但它说this.ViewChildComponent.someMethod() is undefined.我有所有的依赖项,例如提供ViewChildComponent者的服务.我甚至前进了一步,并致电viewChildComponent其服务决定someMethod();

任何帮助都是极好的.

小智 8

如果你有例如

class TestedComponent() {
     @ViewChild('ChildComp') public variableChildComponent: ChildComp;
}
Run Code Online (Sandbox Code Playgroud)

在测试规范文件中声明子组件和测试组件:

beforeEach(() => {
  TestBed.configureTestingModule({
     declarations: [ TestedComponent, ChildComp]
  })
  fixture = TestBed.createComponent(TestedComponent);
  comp = fixture.componentInstance;
  spyOn(comp.variableChildComponent, 'someMethod').and.returnValue(true);
});
Run Code Online (Sandbox Code Playgroud)

这应该有效。

  • 这不是一个好的解决方案,您正在创建对 ChildComp 的硬依赖。如果它停止工作,您的测试将失败,如果它改变行为,测试可能会失败。更好的方法是创建子组件存根,如官方 Angular 文档 https://angular.io/guide/testing#nested-component-tests 中所述,或使用 ng-mocks 库来模拟子组件 https://www.npmjs.com /包/ng-mocks (2认同)

cod*_*pic 5

@DanielDrozzel 的回答可能会解决您的问题,但本质上它是有缺陷的,不是一个好的做法。我想提供一个替代方案。在 Daniel 的回答中,当您使用时declarations: [ TestedComponent, ChildComp],您会在TestedComponent和之间的单元测试中创建紧密耦合ChildComp。如果子组件停止工作,您的测试将失败,如果它改变行为,则测试可能会失败。

这并不总是一件坏事,但有时它会咬你。最好使用官方 Angular 文档https://angular.io/guide/testing#nested-component-tests或一个非常有用的ng-mocks库中提到的组件存根 。上面Angular Docks 中提到的第三个选项是,NO_ERRORS_SCHEMA但是如果您想测试是否从父组件调用子组件的方法,则不能使用它。

使用 ng-mocks 库你需要做的就是交换

declarations: [ TestedComponent, ChildComp] 在丹尼尔的回答中

declarations: [ TestedComponent, MockComponent(ChildComp)]

并且可以在不创建对子组件的硬依赖的情况下测试父组件。