测试eventEmitter的最佳方法是什么?

问题描述 投票:2回答:1

假设我有一个像这样的简单组件:

@Component({
  selector: 'my-test',
  template: '<div></div>'
})

export class test {

  @Output selected: EventEmitter<string> = new EventEmitter<string>();

  public onSelect(event: any) {
    this.selected.emit(event.data);
  }
}

测试它的最佳方法是什么?我见过这样的订阅:

it('should emit the selected item', (done) => {

  myTest.selected.subscribe((result) => {

    expect(result).toBe('123');
    done();
  }
  //Act
  myTest.onSelect({data:'123'});
}

或者像这样的间谍:

it('should emit the selected item', () => {

  spyOn(myTest.selected, 'emit');
  //Act
  myTest.onSelect({data:'123'});
  //Assert
  expect(myTest.selected.emit).toHaveBeenCalledWith('123');
}

这两个结构通过了测试。我认为第二个更简单,所以我的问题是:这两个结构是否相同?是否有理由更好地使用第一次测试而不是第二次测试?为什么?

谢谢你的时间。

javascript angular unit-testing jasmine
1个回答
1
投票

他们以不同的方式测试同样的事情。

我同意你的第二种形式更容易阅读,因为

  1. AAA语法从上到下而不是在回调内部流动
  2. 你正在测试直接影响(称为emit

这与测试在代码中不可见的间接效果(subscribe被调用)形成对比。

© www.soinside.com 2019 - 2024. All rights reserved.