【发布时间】:2021-02-26 16:42:26
【问题描述】:
在我的项目中,我使用 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
如何模拟数据并消除错误?
附:代码中有定义模拟数据matDialogDataMock和MatDialogRefMock。
关闭:我不知道为什么,当我编辑代码时,我收到消息:'看起来你的帖子主要是代码;请添加更多详细信息。'
【问题讨论】:
-
你没有显示matDialogDataMock的定义,是不是忘记初始化了?
标签: angular typescript unit-testing jasmine karma-jasmine