Блок модульных испытаний AngularJS с кармой

0

Я создал приложение календаря, и я пытаюсь создать единичный тест, чтобы показать, где янв 1, 2016 будет отображаться в календарном массиве, который должен находиться в

$ scope.weeks [0] [5]

Тем не менее, когда я тестирую свой массив, я продолжаю получать неопределенный элемент в первом элементе массива.

Вот ошибка:

TypeError: Невозможно прочитать свойство "0" неопределенного

Не знаю, где я ошибаюсь. Любая помощь будет оценена по достоинству.

Вот мой код модульного теста:

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);
    });
});

Вот код из моего приложения:

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);
})
Теги:
arrays
unit-testing

1 ответ

2
Лучший ответ
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);
    });
});

Забыл добавить $ scope. $ Apply() для $ watch для стрельбы. Также были мои параметры в неправильном порядке. Если бы:

var range = CalendarRange.getMonthlyRange (новая дата (newDate.month, newDate.year, 1));

Когда это должно было быть так:

var range = CalendarRange.getMonthlyRange (новая дата (newDate.year, newDate.month, 1));

Он установил год на месяц 1, а затем на 2016 год. Давая мне этот расчет: 2016/12 = 168; 1900 + 168 = 2068.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню