[英]How do I test my Angular scope functions in karma + jasmine?
I'm fairly new to Angular and very new to Jasmine testing. 我对Angular不太熟悉,对Jasmine测试也不陌生。 I have a function in my controller at pushes an object into an empty array (object taken from json data).
我的控制器中有一个函数,用于将一个对象推入一个空数组(从json数据中获取的对象)。
my controller with the functions pertaining to the cart: 我的控制器具有与购物车有关的功能:
$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;
}
My test: 我的测试:
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);
})
});
The error I come back with when running the test: 运行测试时出现的错误:
TypeError: undefined is not an object (evaluating 'choc.id')
I thought I was pushing an object into the array? 我以为我正在将一个对象推入数组? Am I missing something?
我想念什么吗? Should I include the JSON file if it helps?
如果有帮助,是否应该包括JSON文件?
Any guidance would help. 任何指导都会有所帮助。 Thank you!
谢谢!
You're not passing in a parameter to $scope.addItemToCart
. 您没有将参数传递给
$scope.addItemToCart
。 So when it tries to read choc
it can't because it's undefined
. 因此,当它尝试读取
choc
,因为它是undefined
,所以不能。
This line is causing the error: 此行导致错误:
beforeEach(function(){
scope.addItemToCart(); // No parameter being passed in
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.