【问题标题】:Angular/Jasmine - Do Spies work if invoked on ngOnInit?Angular/Jasmine - 如果在 ngOnInit 上调用,间谍会工作吗?
【发布时间】:2019-02-16 11:56:32
【问题描述】:

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

给定组件的我的 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 上调用间谍?我不明白为什么它们不起作用,但你永远不知道!

提前致谢,

蒂亚戈

【问题讨论】:

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


    【解决方案1】:

    问题是,OnInit 在创建 spy 之前被调用。 那是因为您可能在 beforEach 块中调用 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();
    });
    

    【讨论】:

    • 非常感谢阿米特,做到了:)
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2017-09-26
    相关资源
    最近更新 更多