构造函数中的单元测试变量

Unit-testing variables in the constructor

在我的项目中我使用 angular。 变量在组件之一的构造函数中初始化:

constructor(
  private dialogRef: MatDialogRef<MyComponent>,
  @Inject(MAT_DIALOG_DATA) public data: any,
  private fb: FormBuilder
) {
  this.array1 = this.data.filter(item => item.active);
  this.array2 = this.data.filter(item => !item.active);
}

在 component.spec.ts 我有:

class MatDialogRefMock {
  close() {
    return {};
  }
}

const matDialogDataMock = [
  {
    id: 1,
    name: 'name',
    active: true
  },
  {
    id: 2,
    name: 'name2',
    active: false
  }
];

describe('TestComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let dialogRef: MatDialogRef<TestComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        TestComponent
      ],
      providers: [
        { provide: MAT_DIALOG_DATA, useValue: matDialogDataMock },
        { provide: MatDialogRef, useClass: MatDialogRefMock }
      ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientTestingModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    dialogRef = TestBed.inject(MatDialogRef);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

我收到一个错误:

TypeError: Cannot read property 'filter' of undefined

如何模拟数据并消除错误?

P.S。代码中有mock data的定义matDialogDataMockMatDialogRefMock

关闭:我不知道为什么,当我编辑代码时,我收到消息:'It looks like your post is mostly code; please add some more details.'

您需要定义在实例化TestComponent时注入的matDialogDataMock和MatDialogRefMock。

 providers: [
        { provide: MAT_DIALOG_DATA, useValue: matDialogDataMock },
        { provide: MatDialogRef, useClass: MatDialogRefMock }
      ]

如果你通过这个(只是为了检查它是否有效)你就不会得到过滤器错误

  providers: [
    { provide: MatDialogRef, useValue: {} },
    { provide: MAT_DIALOG_DATA, useValue: [] },
  ],

发现错误。 如果有人有相同的消息 - MAT_DIALOG_DATA 应该是一个对象,而不是数组。

就我而言:

providers: [
  { provide: MAT_DIALOG_DATA, useValue: { data: matDialogDataMock } },
  { provide: MatDialogRef, useClass: MatDialogRefMock }
]