I recently started learning Angular and am new to Jasmine testing. I have a function in my controller that adds an object from JSON data into an empty array.
My controller with the cart-related functions:
$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;
}
Test Scenario:
describe('Controller: ChocoListCtrl', function () {
beforeEach(module('App'));
var scope, ctrl;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
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);
})
});
When running the test, I encountered the following error:
TypeError: undefined is not an object (evaluating 'choc.id')
Despite pushing an object into the array, are there any missing elements or should I consider including the JSON file for assistance?
Any advice or guidance would be greatly appreciated. Thank you!