javascript - 在单元测试时用值实例化绑定(bind) Controller

标签 javascript angularjs unit-testing jasmine

我正在尝试测试驱动绑定(bind)到指令的 Controller 。

app.module('App')
.directive('myDirective', function() {
    return {
        templateUrl: '../my-directive.html',
        scope: true,
        bindToController: {
            model: '='
        },
        controller: 'DirectiveCtrl as DirectiveCtrl'
    };
})
.controller('DirectiveCtrl', function() {
    var DirectiveCtrl = this,
        model = DirectiveCtrl.model;

    DirectiveCtrl.resetValue = function() {
        DirectiveCtrl.model = model;
    };
});

在测试中,

describe('DirectiveCtrl', function() {
    var DirectiveCtrl,
        model = {
            id: 'id',
            name: 'name'
        };

    beforeEach(module('App'));

    beforeEach(inject(function($controller) {
        DirectiveCtrl = $controller('DirectiveCtrl');
        // code to initialize controller with model value;
    }));

    it('resets the default value', function() {
        DirectiveCtrl.resetValue();
        expect(DirectiveCtrl.model).toEqual(model);
    });
});

我想以与有界 Controller 在指令编译期间的行为类似的方式初始化 Controller 。我怎样才能做到这一点?

最佳答案

我终于在 Angular 中找到了解决方案 $controller decorator 。第二个参数采用具有绑定(bind)值的对象。

所以测试是,

describe('DirectiveCtrl', function() {
  var DirectiveCtrl,
    model = {
        id: 'id',
        name: 'name'
    };

  beforeEach(module('App'));

  beforeEach(inject(function($controller) {
    DirectiveCtrl = $controller('DirectiveCtrl', {
        model: model
    });
  }));

  it('resets the default value', function() {
    DirectiveCtrl.resetValue();
    expect(DirectiveCtrl.model).toEqual(model);
  });
});

关于javascript - 在单元测试时用值实例化绑定(bind) Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35897077/

相关文章:

javascript - 为多个模块重用指令

java - Spock 使用 Mockito 测试 Kotlin 类

c# - 在 .NET Core 测试项目中构建时禁用/阻止 XUnit 警告

javascript - 在 WEB 应用程序中隐藏已选定选项卡的超链接按钮

javascript - 在 .js 文件中使用 ASP.Net 标签?

javascript - 使用 VS2008 测试 ASP.NET MVC 应用程序时,JS 文件未更新

javascript - require.js 使用来自不同模块的 AngularJS 指令

angularjs - 模块不可用,但具有正确的模块名称并加载它

angular - 无法读取未定义的属性 'ngOnInit' 'getData' -Angular-单元测试-jasmine

javascript - jsoup 以键值对的形式从网页检索数据