【问题标题】:Unit testing directive with controllerAs using Jasmine使用 Jasmine 的带有控制器的单元测试指令
【发布时间】:2018-12-04 03:08:53
【问题描述】:

我是 Jasmine 单元测试的新手,这是我第一次尝试使用控制器测试指令。我的指令和控制器的结构略有不同,我在任何博客或 stackoverflow 问题中都没有看到。我正在努力访问函数 _testSampleFunction() 以在我的测试用例中进行测试。这里的缺点是我无法更改指令的体系结构,我想相应地编写测试用例。任何帮助将不胜感激!

以下是我的控制器的定义方式:

(function () {
'use strict';

angular.module('myApp',[])
        .directive('myDirective', myDirective);

function myDirective()
{
        var directive ={
        template : '<div></div>',
        controller : myController,
        controllerAs : 'vm',
        scope: {},
        };

        myController.$inject =['$scope'];
        return directive;

    function myController($scope)
    {
        var vm = this;
        init();

        function init()
        {
            vm.TestSampleFunction = _testSampleFunction;
        }

        function _testSampleFunction()
        {
            return 'my directive';
        }

    }

}})(window.angular);    

这里是 plunker(包括 spec.js):Demo Plunker

提前致谢!

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    指令测试使用真实控制器,因此您无需在测试中进行任何控制器设置。

    我已经更新了您的Plunker,其中包含一个通过视图进行测试的示例,以及如何获取控制器。

    指令测试很有用,因为您知道控制器和视图被正确绑定 - 我主要(除了我不能的奇怪情况)通过视图测试所有内容(例如单击页面中的某些内容并检查视图会相应更新)。

    【讨论】:

    • 谢谢。那真的很管用!!实时,我必须使用 templateURL。我应该如何配置它?我查看了各种帖子,有些帖子说要使用 $templateCache、$httpBackend,有些帖子建议使用 Karma。
    猜你喜欢
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多