我有一个组件,该组件使用服务打开模式对话框,用户可以在其中选择两个选项{true,false}之一。我想编写隔离的测试(不创建Testbed)。我的问题是,回调根本不会执行(测试失败,因为未分派动作)。
如何测试回调内部的行为?
bla.component.ts
onCancelClicked(): void {
this.unsavedChangesService.openUnsavedChangesModal().subscribe((leaveWithoutSaving: boolean) => {
if (leaveWithoutSaving) {
if (!this.savedChangesExisting()) {
this.store.dispatch(new DeleteDraft(this.id));
} else {
this.store.dispatch(new ResetUnsavedChanges());
}
this.store.dispatch(new DeactivateEditMode());
}
});
}
}
let unsavedChangesServiceMock: any = {
openUnsavedChangesModal: jasmine.createSpy().and.returnValue({
subscribe: jasmine.createSpy().and.returnValue(of(true))
})
};
....
it('bla', () => {
const expectedDeactivateEditModeAction: any = new DeactivateEditMode();
sut['unsavedChanges'] = {[1]: 'something' };
sut['draftsOfTTB'] = undefined;
sut.onCancelClicked();
expect(sut.store.dispatch).toHaveBeenCalledWith(expectedDeactivateEditModeAction);
}
....
答案 0 :(得分:0)
您拥有异步代码,因此您需要按照示例https://codecraft.tv/courses/angular/unit-testing/asynchronous/
中的说明使用异步代码测试