带有templateUrl和隔离范围的角度测试指令

Var*_*eth 3 javascript jasmine angularjs karma-jasmine

angular.js的新功能,无法弄清楚如何使用templateUrl和隔离范围编写指令测试.

这是我的控制器

(function(){
angular.module('buttons')
    .controller('buttonController', ['$scope', function($scope){

        //primary button
        $scope.primaryButton = { name: 'Submit'};
})();
Run Code Online (Sandbox Code Playgroud)

这是我的观点index.html&

<div class="layoutLeft">
        <p>Primary Button</p>
        <primary-button info="primaryButton"></primary-button>
    </div>
Run Code Online (Sandbox Code Playgroud)

初级button.html

<button class="{{buttonInfo.class}}">{{buttonInfo.name}}</button>
Run Code Online (Sandbox Code Playgroud)

这是我的指示

(function(){
    angular.module('buttons')
        .directive('primaryButton', function() {
            return {
                restrict: 'EA',
                scope: {
                    buttonInfo: '=info'
                },
                templateUrl: 'scripts/local/views/primary-button.html'
            }
        })
    })();
Run Code Online (Sandbox Code Playgroud)

这是我的测试

(function(){
    beforeEach(angular.mock.module('buttons'));
describe('Buttons Directive Test', function(){

    var $compile, $scope, $httpBackend;

    beforeEach(module('templates'));

    beforeEach(inject(function(_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $scope = _$rootScope_.$new();

        $scope.primaryButton = {name: 'Save'};

        elm = angular.element("<primary-button info='buttonInfo'></primary-button>");
        e = $compile(elm)($scope);
        e.digest();
    }));

    it('should do something', function(){
        expect(e.html()).toContain($scope.primaryButton);
    });
});
Run Code Online (Sandbox Code Playgroud)

})();

我正在使用茉莉和业力进行测试,有人可以指导我做错了什么

Pet*_*ell 6

编辑:这是一个傻瓜演示非常接近您的代码正在做什么.您修复的问题代码存在多个问题:

http://plnkr.co/edit/QXprEUof2Ps0Vivg4L34?p=preview

  1. 在您的测试中,您调用e.digest(),这将无法工作,因为您无法消化元素...您应该调用$ scope.$ digest.
  2. e.html()不包含该JSON blob.我将其解释为希望它包含名称标签......
  3. info ='buttonInfo'将信息绑定到outerscope中的属性buttonInfo,但您将其称为'primaryButton'.将$ scope.primaryButton重命名为$ scope.buttonInfo
  4. 您使用了一些并非完全必要的下划线,但在注入compile,rootscope时,这并不是什么大问题
  5. 我使用内联模板而不是仅为plunkr加载它,但加载它没有任何问题
  6. 因为你的指令是我添加'replace'的元素,它用直接按钮替换元素.考虑将其改为属性.

我的plunkr已通过茉莉花测试按钮的工作演示.如果您需要更多帮助,请告诉我.祝AngularJS好运.

(老答复)

==============

您将需要使用类似nghtml2js的内容来加载模板并使模板缓存可用.

使用nghtml2js

这是你的第一个问题.第二个问题是通过在编译后调用该元素上的isolateScope()来完成隔离范围.记录在elem上调用它的结果,你会找到你所追求的属性.

e.isolateScope()
Run Code Online (Sandbox Code Playgroud)