【问题标题】:Karma/Jasmine testing custom directive controllerKarma/Jasmine 测试自定义指令控制器
【发布时间】:2014-05-01 21:29:03
【问题描述】:

我正在尝试使用 Karma + Jasmine 测试 AngularJS 自定义指令。我找到了一种方法来检查网络上的许多参考资料。但解决方案似乎不是正确的方法。我们先来看一个例子,这是test.js:

angular.module("app", [])
  .directive("test", function() {
    return {
      restrict: 'E',
      scope: {
        defined: '='
      },
      templateFile: "test.html",
      controller: function($scope) {
        $scope.isDefined = function() {
          return $scope.defined;
        };
      }
    };
  });

describe("Test directive", function() {
  var elm, scope;

  beforeEach(module("app"));
  beforeEach(module("test.html"));

  beforeEach(inject(function($rootScope, $compile, $injector) {
    elm = angular.element("<test defined='defined'></test>");

    scope = $rootScope;
    scope.defined = false;

    $compile(elm)(scope);
    scope.$digest();
  }));

  it("should not be initially defined", function() {
    expect(elm.scope().$$childTail.isDefined()).toBe(false);
  });
});

现在是指令模板文件test.html:

<button data-ng-click='defined = true'></button>

最后是 karma.conf.js:

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],

    files: [
      'angular.min.js',
      'angular-mocks.js',
      'test.js',
      'test.html'
    ],

    exclude: [],

    preprocessors: {
      "test.html": ['ng-html2js']
    },

    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Firefox'],
    singleRun: true
  });
};

我正在使用以下命令行运行测试:

karma start karma.conf.js

对我来说真正奇怪的是控制器中定义的范围函数只能通过$$childTail 属性访问。如果我尝试直接从元素的范围调用它,我会得到一个未定义的值elm.scope().isDefined()。有人对此有更好的解决方案吗?

谢谢!

【问题讨论】:

    标签: javascript unit-testing angularjs-directive jasmine karma-runner


    【解决方案1】:

    因为您的指令使用隔离范围,而不是

    elm.scope()
    

    你应该可以使用

    elm.isolateScope()
    

    isolateScope 函数在http://docs.angularjs.org/api/ng/function/angular.element 处(简要)解释

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 2017-01-03
      • 2015-01-23
      • 2015-11-12
      • 2015-10-03
      相关资源
      最近更新 更多