【发布时间】:2021-04-23 20:19:59
【问题描述】:
我需要测试一个具有 MAT_DIALOG_DATA 的组件,我什至可以模拟它,但我对接收到的数据属性有问题。
我相信模拟是正确的,但我不知道如何将属性放在变量数据上。
*notifications-edit.component.spec.ts
fdescribe('NotificationsEditComponent', () => {
let component: NotificationsEditComponent;
let fixture: ComponentFixture<NotificationsEditComponent>;
let dialogMock: jasmine.SpyObj<any>;
let dialogRefMock: jasmine.SpyObj<any>;
beforeEach(waitForAsync(() => {
dialogRefMock = jasmine.createSpyObj('MatDialogRef', [
'close',
]);
TestBed.configureTestingModule({
imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
AppModule,
MatDialogModule,
MatFormFieldModule,
MatInputModule,
],
declarations: [ NotificationsEditComponent ],
providers: [
{ provide: MatDialogRef, useValue: dialogMock },
{ provide: MAT_DIALOG_DATA, useValue: {} },
]
})
.compileComponents();
}));
*notifications-edit.component.ts
constructor(
public dialog: MatDialog,
public dialogRef: MatDialogRef<NotificationsEditComponent>,
@Inject(MAT_DIALOG_DATA) public notification: any
) {}
ngOnInit() {
this.form = new FormGroup({
frequency: new FormControl(),
topic: new FormControl(),
title: new FormControl(),
time: new FormControl(),
day: new FormControl(),
body: new FormControl()
})
this.form.setValue({
frequency: this.notification.frequency,
topic: this.notification.topic,
title: this.notification.payload.notification.title,
time: this.notification.time.seconds,
day: this.notification.day.day,
body: this.notification.payload.notification.body
})
}
错误
TypeError: Cannot read property 'notification' of undefined
at NotificationsEditComponent.ngOnInit (http://localhost:9876/_karma_webpack_/webpack:/src/app/modules/notifications/pages/notifications-edit/notifications-edit.component.ts:108:23)
at callHook (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:2521:1)
at callHooks (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:2492:1)
at executeInitAndCheckHooks (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:2443:1)
at refreshView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:9429:1)
at renderComponentOrTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:9528:1)
at tickRootContext (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:10754:1)
at detectChangesInRootView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:10779:1)
at RootViewRef.detectChanges (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.js:22792:1)
at ComponentFixture._tick (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/testing.js:141:1)
【问题讨论】:
标签: angular typescript jasmine karma-jasmine