使用依赖项测试angularjs指令

Tig*_*ger 6 angularjs angularjs-directive

我是AngularJs的新手,并且在尝试使用依赖项测试指令时遇到问题(虽然指令本身按预期工作).我无法在这里或其他资源上找到任何答案.

这是我的代码:

指示:

angular.module('MyApp')
  .directive('appVersion', ['config', function (config) {
    return function (scope, elm) {
      elm.text(config.version);
    };
  }]);
Run Code Online (Sandbox Code Playgroud)

服务(价值):

angular.module('MyApp')
  .value('config', {
    version: '0.1'
  });
Run Code Online (Sandbox Code Playgroud)

测试:

describe('Directive: AppVersion', function () {
    beforeEach(module('MyApp'));

    var element;

    it('should have element text set to config value', inject(function ($rootScope, $compile, config) {
        var scope = $rootScope;
        element = $compile('<app-version></app-version>')(scope);
        expect(element.text()).toBe(config.version);
    }));
});
Run Code Online (Sandbox Code Playgroud)

我的测试失败并显示消息:

Error: Expected '' to be '0.1'.
Run Code Online (Sandbox Code Playgroud)

意味着配置值被正确注入,但$ complile没有使用它.我真的很感激任何帮助.谢谢.

Flo*_*n F 3

您没有指定指令的restrict 属性。当您不指定它时,这意味着 Angular 会查找声明为属性而不是元素的 app-version。

因此,您可以将restrict属性添加到指令中或更改模板:

element = $compile('<div app-version></div>')(scope);
Run Code Online (Sandbox Code Playgroud)