我有一个 Angularjs 应用程序,在执行某些操作之前使用简单的javascript确认。
function TokenController($scope) {
$scope.token = 'sampleToken';
$scope.newToken = function() {
if (confirm("Are you sure you want to change the token?") == true) {
$scope.token = 'modifiedToken';
}
};
}
<div id="tokenDiv">
Token:{{token}} <button ng-click="newToken()">New Token</button>
</div>
现在我想进行端到端测试,以检查视图中是否正确替换了令牌。如何拦截javascript.confirm()
调用,以便它不会停止执行测试?
it('should be able to generate new token', function () {
var oldValues = element('#tokenDiv').text();
element('button[ng-click="newToken()"]').click(); // Here the javascript confirm box pops up.
expect(element('#tokenDiv').text()).not.toBe(oldValues);
});
到目前为止,我已尝试重新定义window.confirm
函数,但实际调用却抱怨它未定义。
我还希望在window.confirm
上设置一个Jasmine间谍,但是使用以下语法spyOn(window, 'confirm');
,它会给我一个错误,说你无法监视null
。
我将如何进行此类测试工作?
答案 0 :(得分:27)
另一种选择是直接创建间谍并自动返回true
:
//Jasmine 2.0
spyOn(window, 'confirm').and.callFake(function () {
return true;
});
//Jasmine 1.3
spyOn(window, 'confirm').andCallFake(function () {
return true;
});
答案 1 :(得分:13)
请咨询这个项目: https://github.com/katranci/Angular-E2E-Window-Dialog-Commands
如果您为对话框创建服务,那么您可以在单元测试中模拟该服务,以使您的代码可测试:
function TokenController($scope, modalDialog) {
$scope.token = 'sampleToken';
$scope.newToken = function() {
if (modalDialog.confirm("Are you sure you want to change the token?") == true) {
$scope.token = 'modifiedToken';
}
};
}
yourApp.factory('modalDialog', ['$window', function($window) {
return {
confirm: function(message) {
return $window.confirm(message);
}
}
}]);
function modalDialogMock() {
this.confirmResult;
this.confirm = function() {
return this.confirmResult;
}
this.confirmTrue = function() {
this.confirmResult = true;
}
this.confirmFalse = function() {
this.confirmResult = false;
}
}
var scope;
var modalDialog;
beforeEach(module('yourApp'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
modalDialog = new modalDialogMock();
var ctrl = $controller('TokenController', {$scope: scope, modalDialog: modalDialog});
}));
it('should be able to generate new token', function () {
modalDialog.confirmTrue();
scope.newToken();
expect(scope.token).toBe('modifiedToken');
});
答案 2 :(得分:7)
在单元测试中,您可以像这样模拟$ window对象:
你的考试:
beforeEach(function() {
module('myAppName');
inject(function($rootScope, $injector) {
$controller = $injector.get('$controller');
$scope = $rootScope.$new();
var windowMock = { confirm: function(msg) { return true } }
$controller('UsersCtrl', { $scope: $scope, $window: windowMock });
});
});
你的控制器:
myAppName.controller('UsersCtrl', function($scope, $window) {
$scope.delete = function() {
var answer = $window.confirm('Delete?');
if (answer) {
// doing something
}
}
});