ฉันกำลังพยายามได้รับความครอบคลุมการทดสอบ 100% สำหรับคำสั่ง คำสั่งมีตัวควบคุมพร้อมฟังก์ชันที่ใช้เมธอด window.confirm
'use strict';
(function() {
angular
.module('app')
.directive('buttonToggle', buttonToggle);
function buttonToggle() {
var buttonToggleController = ['$scope', function($scope) {
$scope.toggle = function() {
var confirmResponse = (window.confirm('Are you sure?') === true);
if(confirmResponse) {
$scope.on = !$scope.on;
}
return $scope.on;
};
}];
return {
restrict: 'E',
templateUrl: 'client/modules/buttonToggle/buttonToggle.html',
replace: true,
scope: {
on: '='
},
controller: buttonToggleController
};
}
})();
ฉันได้ทดสอบเพื่อให้แน่ใจว่าทุกอย่างถูกกำหนดไว้แล้ว แต่ฉันไม่สามารถป้อนคำสั่ง if
ในเมธอด $scope.toggle
ของคอนโทรลเลอร์ได้
describe('The buttonToggle directive', function() {
var $compile,
$scope,
btElement = '<button-toggle></button-toggle>',
compiledElement,
window,
confirm,
btElementPath = 'client/modules/buttonToggle/buttonToggle.html',
btController;
beforeEach(module('app'));
beforeEach(module(btElementPath));
beforeEach(inject(function(_$compile_, _$rootScope_, $templateCache, $window) {
$compile = _$compile_;
window = $window;
spyOn(window, 'confirm');
$scope = _$rootScope_.$new();
var template = $templateCache.get(btElementPath);
$templateCache.put(btElementPath, template);
var element = angular.element(btElement);
compiledElement = $compile(element)($scope);
$scope.$digest();
btController = element.controller('buttonToggle', {
$window: window
});
scope = element.isolateScope() || element.scope();
}));
it('should be defined', function() {
expect(compiledElement.html()).toContain('btn');
});
describe('buttonToggle controller', function() {
it('should be defined', function() {
expect(btController).not.toBeNull();
expect(btController).toBeDefined();
});
describe('toggle', function() {
it('should be defined', function() {
expect(scope.toggle).toBeDefined();
});
it('should confirm the confirmation dialog', function() {
scope.toggle();
expect(window.confirm).toHaveBeenCalled();
});
});
});
});
ฉันเดาว่ามันเกี่ยวข้องกับการเยาะเย้ยบริการ $window
แต่ฉันไม่แน่ใจว่าจะสามารถทดสอบได้หรือไม่เนื่องจากไม่มีการประกาศทั่วโลก ดังนั้นฟังก์ชั่นของคอนโทรลเลอร์คือ "ทดสอบหน่วย" ได้อย่างสมบูรณ์หรือไม่? ถ้าไม่ ฉันควรเขียนตัวควบคุมของคำสั่งในไฟล์แยกต่างหากและใช้ angular.module.controller
หรือไม่ ถ้าใช่ ฉันจะทดสอบได้อย่างไร หรือฉันพลาดอะไรไป?
confirm
เช่นเดียวกับalert
บล็อกการทำงานของสคริปต์ - person charlietfl   schedule 26.01.2016