我有一个
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上设置一个茉莉花间谍,但是在以下语法中spyOn(window,’confirm’);它给我一个错误,说你不能间谍空.
我如何进行这样的测试工作?
解决方法
E2E测试
请咨询本项目:
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'; } }; }
modalDialog服务
yourApp.factory('modalDialog',['$window',function($window) { return { confirm: function(message) { return $window.confirm(message); } } }]);
modalDialogMock
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'); });