Reputation: 47
I'm fairly new to Angular and very new to Jasmine testing. I have a function in my controller at pushes an object into an empty array (object taken from json data).
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?
Any guidance would help. Thank you!
Upvotes: 0
Views: 797
Reputation: 2818
You're not passing in a parameter to $scope.addItemToCart
. So when it tries to read choc
it can't because it's undefined
.
This line is causing the error:
beforeEach(function(){
scope.addItemToCart(); // No parameter being passed in
})
Upvotes: 1