angularJS单元测试promise

时间:2016-01-04 20:53:09

标签: angularjs unit-testing promise angular-promise

如何在.then()中单元测试$ scope变量?

我尝试对调用外部API的函数进行单元测试,并在apicall的.then()中处理该api调用的错误/成功。

function submitPayment() {
        //Create post object based off the selected payment method
        var postObj = {
            'premiumDue' : $scope.premiumDue, 
            'effectiveDate' : $scope.effectiveDate
        };

        myPayService.submitPayment(postObj).then(function(responseData){
            if(!responseData.errors) {
                $scope.transactionDetails = [
                    {
                        id: 'transaction-date',
                        label: 'Transaction Date',
                        value: $scope.formattedCurrentDate
                    },
                    {
                        id: 'ammount',
                        label: 'Ammount',
                        value: "$"+$scope.premium.toFixed(2)
                    },      
                ];
            } else {
                $scope.submitError = true;
            }
        });
    }

这很简单,它在实践中有效,但我不确定如何围绕它构建单元测试。我想测试并期望mockedTransactionDetails = $ scope.transactionDetails。

如何对此功能进行单元测试以进行测试?每次我尝试我都得到$ scope.transactionDetails未定义。

到目前为止我的单元测试:

it('should handle submit payment success and set transaction details', function () {
                //set up transaction details now
                $scope.premium = 123.45;
                $scope.effectiveDate = "2016-01-01";
                $scope.formattedCurrentDate = "2016-01-04";

                var submitData = {
                    'premiumDue' : $scope.premium, 
                    'effectiveDate' : $scope.effectiveDate
                };
                var result;
                var promise = myPayService.submitPayment(submitData);
                var mockTransactionDetails = [
                    {
                        id: 'transaction-date',
                        label: 'Transaction Date',
                        value: $scope.formattedCurrentDate
                    },
                    {
                        id: 'ammount',
                        label: 'Ammount',
                        value: "$"+$scope.premium.toFixed(2)
                    },  
                ];

                //Resolve the promise and store results
                promise.then(function(res) {
                    result = res;
                });
                //Apply scope changes
                $scope.$apply();
                expect(mockTransactionDetails).toEqual($scope.transactionDetails);
            });

结果出现在空对象中,并且$ scope.transactionDetails未定义。我不确定我做错了什么?

0 个答案:

没有答案