Angular/Jasmine - 如果在 ngOnInit 上调用,Spies 是否工作?

标签 angular unit-testing jasmine karma-jasmine karma-runner

我有一个响应式表单,我将其拆分为更小的组件,以便能够更好地单独管理每个表单控件。我依靠事件发射器能够将每个控件的状态传达给管理整个表单状态的“父”组件。

我的给定组件的 ngOnInit 方法如下所示:

@Output() formReady: EventEmitter<FormControl> = new EventEmitter();

ngOnInit() {
    (some other unrelated logic here...)
    this.formReady.emit(this.userIdFormControl);
  }

我尝试为该组件编写的测试非常简单

it('should emit formReady event when component is initialised', () => {
    spyOn(component.formReady, 'emit');
    expect(component.formReady.emit).toHaveBeenCalled();
  });

然而,这个测试失败了,因为 Spy 永远不会被调用(尽管如果我向 ngOnInit 添加一个 clg 语句,我可以看到它被打印了预期的次数)。

我的问题是:是否可以在 ngOnInit 上调用 Spies?我不明白为什么它们不起作用,但你永远不知道!

提前致谢

蒂亚戈

最佳答案

问题是,OnInitspy 创建之前被调用。 那是因为您可能在 beforEach block 中调用了 fixture.detectChanges()。只需删除它并在您的规范中调用它。

it('should emit formReady event when component is initialised', () => {
    spyOn(component.formReady, 'emit');
    fixture.detectChanges()
    expect(component.formReady.emit).toHaveBeenCalled();
});

或者您可以在您的规范中再次调用 ngOnInit() 方法以查看它是否正常工作。

it('should emit formReady event when component is initialised', () => {
      spyOn(component.formReady, 'emit');
      component.ngOnInit();
      expect(component.formReady.emit).toHaveBeenCalled();
});

关于Angular/Jasmine - 如果在 ngOnInit 上调用,Spies 是否工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54722798/

相关文章:

html - 在内容加载之前隐藏 css 中的底部边框

angularjs - 使用 Jasmine 进行 Angular 测试

javascript - 如何使用 Jasmine 测试点击事件内的函数调用

Angular Material 对话框 : How to update the injected data when they change in the parent component?

angular - 路由守卫导致错误的路由导航行为

unit-testing - 在 Intellij 中,一个模块是否有可能依赖于另一个模块的测试

objective-c - objective-c -OCMock和 stub ?

eclipse - 在 OS X 上使用 Eclipse 设置 Google 测试 (gtest)

node.js - jasmine-node waitsFor() 停止所有 future 的运行()

html - 如何在单独的文件中加载 ng-template?