2017-01-29 51 views
0

我对Angular相当陌生,对Jasmine测试非常新颖。我在我的控制器中有一个函数,将一个对象推入一个空数组(从json数据中提取对象)。如何测试我的角度范围功能在业力+茉莉花?

我与功能有关的车控制:

$scope.cart = []; 

    $scope.addItemToCart = function(choc) { 
    var cartItem = readCartItem(choc.id); 
    if(cartItem == null) { 
     //if item doesn't exist, add to cart array 
     $scope.cart.push({type: choc.type, id: choc.id, price: choc.price, quantity: 1}) 
    } else { 
     //increase quantity 
     cartItem.quantity++; 
    } 
    } 

    $scope.cartTotal = function() { 
    var sum = 0; 
    $scope.cart.forEach(function(item) { 
     sum += item.price * item.quantity; 
    }); 
    return sum; 
    } 

    $scope.getTotalQuantity = function() { 
    var totalItems = 0; 
    $scope.cart.forEach(function(item) { 
     totalItems += item.quantity; 
    }); 
    return totalItems; 
    } 

    $scope.clearCart = function() { 
    $scope.cart.length = 0; 
    } 

    $scope.removeItem = function(choc) { 
    $scope.cart.splice(choc,1); 
    } 

    function readCartItem(id) { 
    //iterate thru cart and read ID 
    for(var i=0; i<$scope.cart.length; i++) { 
     if($scope.cart[i].id === id) { 
     return $scope.cart[i] 
     } 
    } 
    return null; 
    } 

我的测试:

describe('Controller: ChocoListCtrl', function() { 

    beforeEach(module('App')); 

    var scope, ctrl, json; 

    beforeEach(inject(function ($controller, $rootScope) { 


    scope = $rootScope.$new(); 
    // ChocoListCtrl = $controller('ChocoListCtrl', {}); 
    ctrl = $controller("ChocoListCtrl", { $scope:scope }) 
    })); 

    it('should be defined', function(){ 
    expect(ctrl).toBeDefined(); 
    }); 

    it('should have an empty cart', function(){ 
    expect(scope.cart.length).toBeLessThan(1); 
    }); 

    describe('cart functions', function(){ 
    beforeEach(function(){ 
     scope.addItemToCart(); 
    }) 

    it('should add objects into the cart', function(){ 
     expect(scope.cart.length).toBeGreaterThan(0); 
    }) 
    }); 

错误我回来运行测试时:

TypeError: undefined is not an object (evaluating 'choc.id') 

我我以为我正在推入一个对象到数组中?我错过了什么吗?如果有帮助,我应该包含JSON文件吗?

任何指导都会有所帮助。谢谢!

回答

0

您没有传入参数$scope.addItemToCart。所以当它试图读取choc它不能,因为它是undefined

此行是导致错误:

beforeEach(function(){ 
    scope.addItemToCart(); // No parameter being passed in 
}) 
+0

卫生署。谢谢!!!在我开始做这样的事情之前,我需要我的咖啡...... –

+0

哈哈,没问题,我们都这么做,而且我们都需要我们的咖啡! –