Reputation: 289
I created an app of a calendar and I am trying to create a unit test to show where Jan 1, 2016 will show up on the calendar's array which should be at
$scope.weeks[0][5]
. However, when I test my array I keep getting an undefined on the first element on the array.
Here is the error:
TypeError: Cannot read property '0' of undefined
Not sure where I am going wrong. Any help would be appreciated.
Here is my unit test code:
describe('correctDate', function(){
var $scope, ctrl;
beforeEach(module("calendarDemoApp"));
beforeEach(inject(function($controller, $rootScope){
$scope = $rootScope.$new();
ctrl = $controller('MonthCtrl', {
$scope: $scope
});
$scope.date.month = 0;
$scope.date.day = 1;
$scope.date.year = 2016;
$scope.$apply();
}));
fit('should be the 5th element in array', function(){
expect($scope.date.day).toBe($scope.weeks[0][5].day);
expect($scope.date.month).toBe($scope.weeks[0][5].month);
expect($scope.date.year).toBe($scope.weeks[0][5].year);
});
});
Here is the code from my app:
angular.module('calendarDemoApp', [])
.controller('MonthCtrl', function($scope){
$scope.$watch('date', function(newDate){
var range = CalendarRange.getMonthlyRange(new Date(newDate.year, newDate.month, 1));
var totalWeeks = range.days.length/7;
var weeks = [];
for(i=0; i<totalWeeks; i++){
weeks[i] = [];
for(j=0; j<7; j++){
weeks[i].push(range.days[j+(i*7)]);
}
}
$scope.weeks = weeks;
}, true);
})
Upvotes: 0
Views: 870
Reputation: 289
describe('correctDate', function(){
var $scope, ctrl;
beforeEach(module("calendarDemoApp"));
beforeEach(inject(function($controller, $rootScope){
$scope = $rootScope.$new();
ctrl = $controller('MonthCtrl', {
$scope: $scope
});
$scope.date.month = 0;
$scope.date.day = 1;
$scope.date.year = 2016;
$scope.$apply();
}));
fit('should be the 5th element in array', function(){
expect($scope.date.day).toBe($scope.weeks[0][5].day);
expect($scope.date.month).toBe($scope.weeks[0][5].month);
expect($scope.date.year).toBe($scope.weeks[0][5].year);
});
});
Forgot to add $scope.$apply() for the $watch to fire. Also had my parameters in the wrong order. Had this:
var range = CalendarRange.getMonthlyRange(new Date(newDate.month, newDate.year, 1));
When it should have been this:
var range = CalendarRange.getMonthlyRange(new Date(newDate.year, newDate.month, 1));
It set the year to a month of 1 and then a month of 2016. Giving me this calculation: 2016/12 = 168; 1900+168 = 2068.
Upvotes: 2