对象可能未定义 angular 单元测试

object is possibly undefined angular unit testing

我正在进行单元测试,但出现以下错误

Object is possibly 'undefined'

 it('should set the dataSource filter to the provided argument', () => {
  component.applyFilter('filterValue');
   expect(this.dataSource.filter).toEqual('filterValue');
  })

it('should set the dataSource filter to the provided argument', () => {
   component.applyFilter('filterValue');
   expect(this.DMDataSource.filter).toEqual('filterValue');
 })

我在 expect(this) 中遇到错误,这里的错误是什么。

请告诉我。

您应该在 expect 块中使用 component.dataSource 而不是 this.dataSource

您需要评估 component 实例中定义的 dataSource

it('should set the dataSource filter to the provided argument', () => {
  component.applyFilter('filterValue');
   expect(component.dataSource.filter).toEqual('filterValue');
  })

it('should set the dataSource filter to the provided argument', () => {
   component.applyFilter('filterValue');
   expect(component.DMDataSource.filter).toEqual('filterValue');
 })