情境:
我正在测试我的Angular / Ionic应用程序中的模式是否正常工作。
到目前为止,我可以正确地测试该模式已被调用的事实,但我不知道如何测试该模式的正确关闭。
我已经做了几次尝试,并阅读了类似的问题,但没有找到解决方案。
代码:
控制器:
代码在应用程序中运行良好,它刚刚进行了重构,以方便单元测试。
$scope.open_login_modal = function()
{
var temp = $ionicModal.fromTemplateUrl('templates/login.html',{scope: $scope});
temp.then(function(modal) {
$scope.modal_login = modal;
$scope.modal_login.show();
});
};
$scope.close_login_modal = function()
{
$scope.modal_login.hide();
};
测试:
第一个测试(开放模式)工作正常并通过。第二个测试,我不知道该怎么做。
describe('App tests', function()
{
beforeEach(module('my_app.controllers'));
// mocking the .then method of $ionicModal.fromTemplateUrl (it works)
function fakeTemplate()
{
return {
then: function(modal){
$scope.modal_login = modal;
}
}
}
beforeEach(inject(function(_$controller_, _$rootScope_)
{
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl').and.callFake(fakeTemplate)
};
var controller = $controller('MainCtrl', { $scope: $scope, $rootScope: $rootScope, $ionicModal: $ionicModal });
}));
describe('Modal tests', function()
{
it('should open login modal', function()
{
$scope.open_login_modal();
expect($ionicModal.fromTemplateUrl).toHaveBeenCalled();
expect($ionicModal.fromTemplateUrl.calls.count()).toBe(1);
});
it('should close login modal', function()
{
$scope.close_login_modal();
// How can i test here that the modal has been close?
});
});
});
错误:
这是错误消息:TypeError: Cannot read property 'hide' of undefined
问题:
如何测试模式的封闭性?如何确保函数hide()
已被正确调用?
它与测试中的模式声明有关吗?
非常感谢!
编辑:
这个答案正确地回答了“如何测试模式的关闭”的问题,给出了在打开模式之前要包含的正确解决方案。如果你想知道如何正确侦测一个模态,我已经在一个单独的问题中问过:
Karma-Jasmine: How to properly spy on a Modal?
给定的答案还给出了一般情况下如何窥探前提的规则。
发布于 2015-10-27 16:42:36
您的close测试需要打开模式登录,由于没有发生这种情况,因此您将收到该错误:
我会重写你的测试,比如:
describe('Modal tests', function() {
beforeEach(function(){
$scope.open_login_modal();
});
it('should open login modal', function() {
expect($ionicModal.fromTemplateUrl).toHaveBeenCalled();
expect($ionicModal.fromTemplateUrl.calls.count()).toBe(1);
});
it('should close login modal', function() {
$scope.close_login_modal();
spyOn($scope.modal_login, 'hide');
expect($scope.modal_login.hide()).toHaveBeenCalled();
});
});
因此,这两个测试都需要调用open_login_modal函数,所以我添加了一个beforeEach。你还需要一个间谍的隐藏功能的模式也。
https://stackoverflow.com/questions/33362798
复制相似问题