关于ng-repeat函数的Jasmine测试用例来计算总计

时间:2016-02-11 09:28:35

标签: angularjs karma-jasmine

我需要在计算购物车总数的函数上编写一个测试用例。

我的Html代码

<table> 
    <tr ng-repeat = "x in countrynames">
        <td>{{x.Goods}}</td>
        <td>{{x.City}}</td>
        <td>{{x.Country}}</td>
        <td>{{x.count}}</td>
        <td>{{x.quantity}}</td>
        <td>Total : {{ x.total }}</td>
    </tr>
</table>

控制器文件

var app = angular.module("myApp",[]);
app.controller("myCtrl", function($scope, $http) {

     $http.get("./country.json").then(function(response) {
        $scope.countrynames = response.data.records;
        $scope.getTotal();
    });

    $scope.getTotal = function(){
        var total = 0;
        for(var i = 0; i < $scope.countrynames.length; i++){
            var product = $scope.countrynames[i];
            product.total = (product.quantity * product.count);

        } 
        return total;
    }

});

需要帮助在getTotal函数上编写测试用例,我是jasmine的新手:) 该功能是产品数量和数量的简单乘法逻辑。

谢谢

1 个答案:

答案 0 :(得分:1)

根据您的示例,我没有看到实际使用getTotal函数的位置?

无论如何,这只是一种可以测试getTotal函数的方法:

describe('myCtrl', function () {
var scope, ctrl;

// Load the myApp module, which contains the controller
beforeEach(module('myApp'))

beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    ctrl = $controller('myCtrl', {$scope: scope});
}));

beforeEach(angular.mock.inject(function ($httpBackend) {
    backend = $httpBackend;
}));

it('Test that total matched expected', function () {
    backend.expect("GET", "./country.json").
        respond(200,
        [{
            // insert a sample of your country.json here.
        }]
    );
    scope.$digest();
    expect(scope.getTotal()).toBe(4);  // change 4 to be the number of results you expected.
});