angularjs - 在 Jasmine 测试中获取自定义指令的 Controller 范围

标签 angularjs angularjs-directive jasmine angularjs-scope karma-jasmine

我正在尝试 访问范围附带的 Controller **我的自定义 Angular 指令** Jasmine 测试 .

app.directive('MyDirective', function(){
return {
         template:...,
         scope:...,
         controller: function($scope){
                $scope.clickMe = function() {
                    ....
                  };
            $scope.message = "";
         }
 }

我想在 jasmine 中编写一个测试来验证是否定义了 clickMe 方法。
 it('should have 3 methods', function() {
    expect(dscope).not.toBe(null);
    expect(scope).not.toBe(null);
    expect(angular.isFunction(dscope.clickMe)).toBe(true);
    expect(dscope.message).toBe(true); }

在 beforeEach() 中,我声明了 scope 和 dscope 变量,如下所示:
beforeEach(inject(function(  $rootScope, $compile){
    scope = $rootScope.$new();      

    element = angular.element("<div my-directive></div>");

    //bind the empty scope into the directive
    $compile(element)(scope);

    //access to internal directive scope of our element
    dscope = element.scope();  }));

但是当我运行测试时,我得到“ 期望 false 为真。”* 并期望 undefined 对于 scope.message 不为 null

最佳答案

如果您使用的是 Angular 1.2+,则必须使用...

dscope = element.isolateScope();

代替...

dscope = element.scope();

访问隔离的范围。我无法判断您的范围是否是孤立的,因为您在问题中省略了指令的范围声明,但我想这就是这里发生的事情。

this Github 上的 issue 以解释 .scope() 和 .isolateScope() 之间的区别

关于angularjs - 在 Jasmine 测试中获取自定义指令的 Controller 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182756/

相关文章:

javascript - 自动完成——颜色输入建议文本

javascript - 在 AngularJS 中,为什么终端自定义指令的行为会随着内置指令而改变?

javascript - Angular 代码覆盖错误输出

javascript - angularJS:谷歌地图未加载地点API

javascript - 如何使用 angularjs 显示另一个文本值,而不是显示一个属性的 ng-repeat 现有值?

javascript - "myApp"应用程序中的 Angular JS 表单验证。

javascript - 我可以在 angularjs 指令中使用 JQuery 插件吗?

angularjs - splice() 元素时完成 ng-repeat 的 Angular 指令

angular - 为具有 NgZone 依赖项的组件运行 jasmine 测试

javascript - Protractor 页面对象错误