Ошибка теста Жасмин: Ошибка типа: не удается прочитать свойство 'подписка' из неопределенного - PullRequest
0 голосов
/ 21 октября 2019

Я пишу тест под углом 8, чтобы проверить, был ли вызван метод компонента. В моем случае я проверяю, вызван ли метод removeSettlementConfirmation. Я не уверен, что callThrough или возвращение пустого obserable является лучшим способом проверки, если метод вызывается

Если я пишу

spyOn(component, 'removeSettlementConfirmation').and.callThrough();

Я получаю ошибку TypeError: Невозможно прочитать свойство 'subscribe'из неопределенного

Но если я напишу

spyOn(component, 'removeSettlementConfirmation').and.returnValue({ subscribe: () => {} });

Ошибка исчезнет.

Какой правильный способ тестирования называется этот метод?

Модульный тест

fit('removeSettlementConfirmation should be called', () => {
        let clientCompanyOpiId = 10;
        let title = `Delete Settlement Account`;
        let message = `Are you sure you want to delete this OPI account?`;
        let testConfirmModal = ({
            title: 'Delete Settlement Account',
            message: 'Are you sure you want to delete this OPI account?'
        } as ConfirmModalComponent);
        component.confirmModal = testConfirmModal;
        spyOn(component, 'removeSettlementConfirmation').and.returnValue({ subscribe: () => {} });
        spyOn(clientService, 'getNumberOfTradesWhereOPIIsSetOn').and.returnValue({ subscribe: () => {} });
        component.removeSettlementConfirmation(clientCompanyOpiId);
        expect(component.removeSettlementConfirmation).toHaveBeenCalled();
    });

Код компонента

removeSettlementConfirmation(clientCompanyOpiId: number): void {
        this.clientService.getNumberOfTradesWhereOPIIsSetOn(clientCompanyOpiId)
            .subscribe(
                data => {
                    const assignedTrades = data;
                    const trades = +assignedTrades > 1 ? 's' : '';
                    const message = assignedTrades
                        ? `This OPI account is set on ${assignedTrades} trade${trades}. Are you sure you want to delete it?`
                        : `Are you sure you want to delete this OPI account?`;
                    const title = `Delete Settlement Account`;
                    this.confirmModal.openModal(title, message, clientCompanyOpiId);
                },
                error => {
                    this.alertService.showMessage("Error", "Unable to get Associated Trades for Settlement Account", MessageSeverity.error);
                });
    }  

1 Ответ

0 голосов
/ 21 октября 2019
and.returnValue():

Можно заставить шпиона вернуть предустановленное / фиксированное значение (без необходимости вызова реальных методов с использованием and.callThrough()). Этого можно достичь, связав функцию spyOn() с and.returnValue().

    fit('removeSettlementConfirmation should be called', () => {
                let clientCompanyOpiId = 10;
                let title = `Delete Settlement Account`;
                let message = `Are you sure you want to delete this OPI account?`;
                let testConfirmModal = ({
                    title: 'Delete Settlement Account',
                    message: 'Are you sure you want to delete this OPI account?'
                } as ConfirmModalComponent);
                component.confirmModal = testConfirmModal;
                spyOn(component, 'removeSettlementConfirmation').and.returnValue("mock response"); // with returnValue() you should return the actual mockResponse
                spyOn(clientService, 'getNumberOfTradesWhereOPIIsSetOn').and.returnValue("test"); // with returnValue() you should return the actual mockResponse
                component.removeSettlementConfirmation(clientCompanyOpiId);
                expect(component.removeSettlementConfirmation).toHaveBeenCalled();

                // you can verify by calling the methods and expected response
                const response = component.removeSettlementConfirmation();
                expect(response).toEqaul("mock response");
            });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...