如何在karma + jasmine中测试我的Angular范围函数?

时间:2017-01-29 19:08:21

标签: javascript angularjs json jasmine karma-jasmine

我是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文件吗?

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

1 个答案:

答案 0 :(得分:1)

您未将参数传递给$scope.addItemToCart。因此,当它尝试阅读choc时,它就不会因为它undefined而感到高兴。

此行导致错误:

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