我应该如何使用 karma 和 jasmine 测试确认框的两个结果?我正在运行一些基本测试,这要感谢这里一位乐于助人的人,但我在模拟 ionicPopup 时遇到了困难。
如果我能够从调用该框的 ng-click 一直测试到所有可能的结果,那就太理想了。
查看:
<button ng-click="openPopup()">Open Popup</button>
Controller :
angular.module('starter.thisController', [])
.controller('ThisCtrl', function($scope, $state, $timeout, $ionicPopup) {
$scope.openPopup = function() {
var openPopup = $ionicPopup.confirm({
title: 'Confirm',
template: 'Are you sure?'
});
openPopup.then(function(res) {
if(res) {
$scope.confirmClicked();
}
});
$timeout(function() {
openPopup.close();
}, 5000);
};
$scope.confirmClicked = function() {
alert("User Clicked Confirm!!!");
};
});
当前测试:
describe('This Controller', function() {
var scope, state, timeout, ionicPopup;
ionicPopup = jasmine.createSpyObj('$ionicPopup spy', ['confirm']);
beforeEach(module('starter.thisController'));
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
$controller('ThisCtrl', {
'$scope': scope,
'$state': state,
'$timeout': timeout,
'$ionicPopup': ionicPopup
});
}));
describe('Popup', function() {
it('should be defined', function() {
expect(ionicPopup).toBeDefined();
});
});
});
感谢您提供的任何帮助:D。
最佳答案
我也遇到了同样的问题,我通过使用spyOn解决了它。我会尽力使其适合您的示例。
describe('This Controller', function() {
var scope, state, timeout, $ionicPopup, $q
beforeEach(module('starter.thisController'));
beforeEach(inject(function($rootScope, $controller, _$ionicPopup_, _$q_) {
scope = $rootScope.$new();
$ionicPopup = _$ionicPopup_;
$q = _$q_;
$controller('ThisCtrl', {
'$scope': scope,
'$state': state,
'$timeout': timeout,
'$ionicPopup': $ionicPopup
});
}));
describe('$scope.openPopup', function() {
it('should call confirmClicked function if ok is clicked in the confirm popup', function() {
var deferred = $q.defer();
deferred.resolve(true); //ok is clicked
spyOn($ionicPopup, 'confirm').and.callFake(function(){return deferred.promise});
scope.openPopup();
scope.$digest();
expect(scope.confirmClicked).toHaveBeenCalled();
});
it('should not call confirmClicked if cancel is clicked in the confirm popup', function() {
var deferred = $q.defer();
deferred.resolve(false); //cancel is clicked
spyOn($ionicPopup, 'confirm').and.callFake(function(){return deferred.promise});
scope.openPopup();
scope.$digest();
expect(scope.confirmClicked).not.toHaveBeenCalled();
});
});
});
这里的主要区别是我们注入(inject)真正的 $ionicPopup,然后用 spy On覆盖它的行为。
关于angularjs - 对确认弹出窗口进行单元测试 Ionic 框架 Karma,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39813798/