茉莉花测试中的访问指令属性值



我有一个像这样的示例AngularJS指令<div some-dir="5" />

如何在测试中访问5的此指令属性值?

describe("some-dir", function() {
    var element, scope;
    beforeEach(module('app'));
    beforeEach(inject(function($rootScope, $compile) {
        scope = $rootScope;
        element = angular.element('<div><div id="el1" some-dir="5" /></div>');
        $compile(element)(scope);
        scope.$digest();
    }));
    it('should be able to get the attribute value', function(){
       // get the attr value of some-dir

    });
});

您可以使用其 isolateScope 方法检查元素的作用域值。但是,当您在指令属性旁边传递值时,这将不起作用,因为这些值不会复制到隔离范围内。

在这种情况下,可以使用 element.attributes 方法获取并测试该值。

首先编译你的指令 html:

var element;
beforeEach(inject(function (_$compile_, _$rootScope_) {
    var $compile = _$compile_,
        $scope = _$rootScope_;
    element = $compile('<div my-directive="4" some-value="5"></div>')($scope);
    $scope.$digest();
}));

然后你可以期望元素的 isolateScope 返回一个具有 someValue 属性的对象。

it('should expect some-value as 5', function () {
    inject(function ($injector) {
        // check attribute values using isolateScope
        expect(element.isolateScope().someValue).toEqual(5);
        // check the value right after directive attribute
        expect(element.attr('my-directive')).toEqual('4');
    });
});

下面是一个示例。

最新更新