Как я могу охватить ответ на обещание с помощью Jasmine и Karma

У меня есть функция, которая возвращает и обрабатывает обещание, мне нужно покрыть возврат, который находится внутри then, но я не знаю, как я могу это сделать, сейчас я пытаюсь сделать следующее:

    confirmRemoveUser(user: IUser) {
    this.modalService
        .open('Confirma a exclusão do usuário selecionado?', {
            titleText: 'Confirmando exclusão',
            confirmButtonText: 'Sim',
            cancelButtonText: 'Cancelar',
            closeButtonText: 'Fechar',
            buttonType: 'danger'
        })
        .result.then(
            (result: BentoModalConfirmationCloseReason) => {
                if (result === BentoModalConfirmationCloseReason.Confirm) {
                    if (this.removeUser(user)) {
                        this.toastService.open('Usuário excluído com sucesso!', { type: 'success', close: true });
                    } else {
                        this.toastService.open('Falha ao excluir o usuário!', { type: 'warning', close: true, duration: 0 });
                    }
                }
            }
        );
}

В настоящее время я использую callthrough () и представляю, что с некоторым параметром я могу получить обещание, но я не знаю, как это сделать:

   it('Given_ConfirmRemoveUser_When_UserStepIsCalled_Then_UserIsRemoved', (done) => {

        component.selectedJob = {
        };

        component.selectedArea = {
        };

        component.users = [{
        }];

        spyOn(modalService, 'open').withArgs('This is modal msg').and.callThrough();

        component.confirmRemoveUser(component.users[0]);

        expect(modalService.open).toHaveBeenCalled();
        done();
    });

И мое покрытие похоже на изображение ниже:

Изображение здесь!

ОБНОВИТЬ

Новая ошибка


person Guilherme Prado    schedule 12.12.2019    source источник


Ответы (1)


Ваш тест должен работать, если он переписан следующим образом:

it('Given_ConfirmRemoveUser_When_UserStepIsCalled_Then_UserIsRemoved', (done) => {
    spyOn(modalService, 'open').and.returnValue(Promise.resolve(BentoModalConfirmationCloseReason.Confirm));
    spyOn(toastService, 'open').and.stub();

    component.confirmRemoveUser(component.users[0])
      .then(r => {
        expect(toastService.open).toHaveBeenCalled();
        done();
      })
      .catch(e => fail(e));
});

Вы, вероятно, также хотите знать, что будет отображаться в тосте. Поэтому имеет смысл использовать expect(toastService.open).toHaveBeenCalledWith(?);.

ОБНОВЛЕНИЕ Приведенное выше решение работает только в том случае, если confirmRemoveUser возвращает Promise.

confirmRemoveUser(user: IUser) {
    return this.modalService
    ...

В вашем случае использование функции done не имеет смысла. Вам нужно использовать async и await.

it('Given_ConfirmRemoveUser_When_UserStepIsCalled_Then_UserIsRemoved', async () => {
    spyOn(modalService, 'open').and.returnValue(Promise.resolve(BentoModalConfirmationCloseReason.Confirm));
    spyOn(toastService, 'open').and.stub();

    await component.confirmRemoveUser(component.users[0]);

    expect(toastService.open).toHaveBeenCalled();
});

То же самое можно сделать с помощью fakeAsync и flush.

import { fakeAsync, flush } from '@angular/core/testing';
...
it('Given_ConfirmRemoveUser_When_UserStepIsCalled_Then_UserIsRemoved', fakeAsync(() => {
    spyOn(modalService, 'open').and.returnValue(Promise.resolve(BentoModalConfirmationCloseReason.Confirm));
    spyOn(toastService, 'open').and.stub();

    component.confirmRemoveUser(component.users[0]);
    flush();

    expect(toastService.open).toHaveBeenCalled();
}));
person uminder    schedule 12.12.2019
comment
выглядит хорошо, но у меня появляется следующее сообщение об ошибке Property 'then' does not exist on type 'void' - person Guilherme Prado; 12.12.2019
comment
Я не заметил, что confirmRemoveUser не возвращает Promise, проверьте обновленный ответ. - person uminder; 12.12.2019
comment
Я попробовал 3 решения, но у всех есть это сообщение об ошибке: Cannot read property 'result' of undefined. Я думаю, именно поэтому я не вызвал modalService, чтобы результат был нулевым, поскольку я мог бы вызвать modalService.Open, чтобы он дал мне результат для всплывающего уведомления, чтобы использовать его? - person Guilherme Prado; 12.12.2019
comment
@Guilherme Prado: Причина в том, что modalService.open spy должно возвращать BentoModalConfirmationCloseReason. Я не знаю этого class или interface, но адаптирую свой ответ, делая предположения. - person uminder; 12.12.2019
comment
выдает ошибку, которая обновляется в вопросе, но большое спасибо за помощь в этом, я могу попробовать кое-что, спасибо - person Guilherme Prado; 12.12.2019