情况:
在我的Ionic应用程序中,我正在测试模态的正确打开。
我做了几次尝试,但是我收到了以下错误:
TypeError: Cannot read property 'then' of undefined
功能:
$scope.open_register_modal = function()
{
$ionicModal.fromTemplateUrl('templates/project_register.html', {
scope: $scope
}).then(function(modal) {
$scope.modal_register = modal;
$scope.modal_register.show();
});
};
测试:
describe('App tests', function() {
beforeEach(module('my_app.controllers'));
beforeEach(inject(function(_$controller_, _$rootScope_)
{
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then : function(modal){} // <--- attempt
};
var controller = $controller('MainCtrl', { $scope: $scope, $rootScope: $rootScope, $ionicModal: $ionicModal });
}));
describe('Modal tests', function()
{
it('should open register modal', function()
{
$scope.open_register_modal();
expect($ionicModal).toHaveBeenCalled();
});
});
});
ATTEMPTS:
这些是初始化$ ionicModal的一些尝试:
1。
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then : function(modal){}
};
2。
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then: jasmine.createSpy('$ionicModal.then')
};
3。
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl'),
then: jasmine.createSpy('$ionicModal.fromTemplateUrl.then')
};
4.
$ionicModal = jasmine.createSpyObj('$ionicModal', ['show', 'close','fromTemplateUrl']);
但他们都给出了同样的错误:
TypeError: Cannot read property 'then' of undefined
问题:
如何在测试中传递.then方法?
我如何正确测试ionicModal?
答案 0 :(得分:2)
我对离子知之甚少,但我认为你的错误是希望方法then
是其中的一部分。代码
$ionicModal.fromTemplateUrl('templates/project_register.html', {
scope: $scope
}).then(function(modal) {
$scope.modal_register = modal;
$scope.modal_register.show();
});
可以重构为:
var temp=$ionicModal.fromTemplateUrl(
'templates/project_register.html',
{scope: $scope});
temp.then(function(modal) {
$scope.modal_register = modal;
$scope.modal_register.show();
});
所以方法then
是调用fromTemplateUrl
解决方案可能类似于:
function fakeTemplate() {
return { then:function(){}}
}
$ionicModal = {
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl').and.callFake(fakeTemplate)
};