Karma-Jasmine:如何测试离子模型?

时间:2015-10-23 07:17:32

标签: javascript angularjs ionic-framework jasmine karma-runner

情况:

在我的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?

1 个答案:

答案 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)
    };