Angular 中的单元测试用例轮询服务

时间:2021-01-27 06:32:32

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

 ngOnInit(): void {
    
    this.timeInterval = interval(30000).pipe(startWith(0), switchMap(() => this.deviceService.getDeviceSession())
    ).subscribe((success: any) => {
      this.rowData = success;
      console.log(this.rowData)
      
    }, (error: any) => {
      this.rowData = [];
      if (error.error && error.error.status !== 401) {
        this.toastService.error('Error in loading data');
      }
    }
    
Test Case    

it('should start checking for data after every interval', (done) => {
const dataService = TestBed.get(DeviceService);
// Mock the getStatus function
spyOn(dataService, 'getDeviceSession').and.returnValue(Observable.create().pipe(map(() => 'woo')));
// Should not be initialised yet
expect(component.rowData).toBeUndefined();

setTimeout(()=> {
      expect(component.rowData).toBe('woo');
      done();
},30000);

});

我正在编写这个单元测试用例来检查这个轮询实现,它从服务中获取数据(对象数组)并在 Dom 中更新它。但是测试用例失败了。我不确定我哪里出错了。 获取错误 rowData.forEach 不是函数。请帮助如何解决它

1 个答案:

答案 0 :(得分:1)

使用 Jasmin 的 beforeEach\before 在 it() 之前启动一些数据,而不是在 ngOnInit 中进行。

https://jasmine.github.io/api/3.5/global

因此,如果我正确理解您的操作,您可以在 ngOnInit 生命周期挂钩中启动 rowData 属性。但它在您的 it() 函数中尚不可用。

如果您想在运行测试之前运行一些代码并启动数据,您应该使用 beforeEach() 函数,然后才使用 it()

检查下面的图像: https://miro.medium.com/max/4800/1*CklcdftSg9EFGsU20ZwdJg.png

使用 Angular 和 Jasmine 进行单元测试的一个很好的指南: https://medium.com/swlh/angular-unit-testing-jasmine-karma-step-by-step-e3376d110ab4