After numerous attempts and hours of troubleshooting, I am still unable to successfully integrate Karma with my Angular controller. No matter what I try, the same error persists even when removing expectGET() calls - as soon as $http.flush(); is called.
An error message stating: TypeError: Cannot set property 'totalBeforeDiscounts' of undefined.
The code snippet for my controller is shown below:</p>
<pre><code>var quotePadControllers = angular.module('quotePadControllers', []);
quotePadControllers.controller('QuotesController', ['$scope', '$http', '$q', function($scope, $http, $q){
var blankAddon;
// Initialization and setting default values
var ajaxGetAddOns = $http.get('/?ajax=dbase&where=aons'),
ajaxGetFrames = $http.get('/?ajax=dbase&where=fcats');
$q.all([ajaxGetAddOns, ajaxGetFrames]).then(function(results){
$scope.addons = results[0].data;
$scope.frames = results[1].data;
$scope.pairs = [
{
"frames" : angular.copy($scope.frames),
"addons" : angular.copy($scope.addons),
}
];
});
// Function for adding a new pair
$scope.addPair = function()
{
$scope.pairs.push({
"frames" : angular.copy($scope.frames),
"addons" : angular.copy($scope.addons)
});
};
// Function for removing a pair
$scope.removePair = function()
{
if ( $scope.pairs.length > 1 )
{
$scope.pairs.pop();
}
};
// Continuously updating subtotal and total
$scope.$watch('pairs', function(pairs) {
var totalBeforeDiscounts = 0;
angular.forEach(pairs, function(pair) {
var subTotal = 0;
angular.forEach(pair.addons, function(addon) {
subTotal += addon.added ? addon.price : 0;
});
subTotal += pair.currentFrame !== undefined ? pair.currentFrame.price : 0;
pair.subTotal = subTotal;
totalBeforeDiscounts += subTotal;
});
pairs.totalBeforeDiscounts = totalBeforeDiscounts;
}, true);
}]);
The test code snippet is as follows:
describe('QuotesController', function()
{
beforeEach(module('quotePadApp'));
var ctrl, $scope, $http, frameCatsHandler, addOnsHandler, createController;
// Setting up tests
beforeEach(inject(function($controller, $rootScope, $httpBackend, _$q_) {
$scope = $rootScope.$new();
$http = $httpBackend;
frameCatsResponse = [{"id":145,"price":25,"brand":"mybrand"},
{"id":147,"price":45,"brand":"mybrand"},
{"id":148,"price":69,"brand":"mybrand"}];
addOnsHandler = [{"id":1,"name":"addon1","price":30,"includeIn241":0,"description":null},
{"id":2,"name":"addon2","price":60,"includeIn241":0,"description":null}];
frameCatsHandler = $http.when('GET', '/?ajax=dbase&where=fcats').respond(frameCatsResponse);
addOnsHandler = $http.when('GET', '/?ajax=dbase&where=aons').respond(addOnsHandler);
createController = function()
{
return $controller('QuotesController', {'$scope' : $scope });
};
}));
it('Should request frame cats and addons from the database', function()
{
$http.expectGET('/?ajax=dbase&where=aons');
$http.expectGET('/?ajax=dbase&where=fcats');
createController();
$http.flush();
});
});