首页 > 解决方案 > 预计间谍已被调用

问题描述

我有以下组件和一个显示模式的方法。如果用户通过按下“OK”确认,它将返回一个可观察的真,如果他们取消它返回一个可观察的假。但是,我发现很难应用测试用例来检查是否this.onSwitchWindowClick()Observable.of(true).

public confirmSwitchWindow() {
    const modalConfig: ConfirmModalConfig = new ConfirmModalConfig(
        'modal title',
        'this is the modal message',
        [
            [this.translateService.instant('actions.confirm'), ConfirmButtonActions.YES],
            [this.translateService.instant('actions.cancel'), ConfirmButtonActions.CANCEL],
        ],
        ConfirmIcons.WARN,
    );

    this.confirmService.showConfirmModal(modalConfig, true).pipe(
        mergeMap((action: ConfirmButtonActions) => {
            if (action === ConfirmButtonActions.YES) {
                return Observable.of(true);
            } else {
                return Observable.of(false);
            }
        }),
        catchError((err) => {
            throw Observable.of(err);
        }),
    ).subscribe((value: boolean) => {
        if (value) {
            this.onSwitchWindowClick();
        }
    });
}

这是测试:

it('Should correctly confirm switch from planning window to production', async(() => {
    const spyShowConfirmModal = spyOn(confirmService, 'showConfirmModal').and.returnValue(Observable.of(true));
    const onSwitchWindowClick = spyOn(component, 'onSwitchWindowClick');
    component.confirmSwitchWindow();
    component.returnValue = true;
    expect(spyShowConfirmModal).toHaveBeenCalled();
    spyShowConfirmModal(null, true).subscribe((value) => {
        fixture.detectChanges();
        expect(onSwitchWindowClick).toHaveBeenCalled();
    });
}));

测试失败:"... FAILED: Expected spy onSwitchWindowClick to have been called."

如何解决这个问题?

标签: angularunit-testingjasminekarma-jasmine

解决方案


推荐阅读