我应该在测试时将原始或编译/链接元素附加到正文吗?

时间:2014-02-06 18:56:50

标签: angularjs jasmine karma-runner jasmine-jquery

当我仅使用编译和链接设置测试时,该指令被触发但该元素仅存在于limbo中,因为如果我没有将它显式添加到DOM,则下面的测试会失败。

我只是想知道是否应该将预编译的angular.element(...)添加到DOM或编译/链接的linkFr(scope),或者我是否会将这一切都搞错。

测试设置

beforeEach(inject(function ($rootScope, $compile) {

    var linkFn, el;

    rootScope = $rootScope;

    scope = $rootScope.$new();

    el = angular.element('\
        <a id="testClickConfirm" href="" ng-click="deleteFn()" click-confirm="Test confirmation message">Delete</a>\
    ');

    // $('body').append(el);

    // The $compile method returns the directive's link function
    linkFn = $compile(el);

    // The link function returns the resulting DOM object
    element = linkFn(scope);

    $('body').append(element);

}));

测试

只要我调用$('body').append(el);$('body').append(element);所有测试都通过,否则它们都会失败。

it('should be added to dom',function(){

    expect(element).toExist();
    expect(element).toBeInDOM();
    expect(element).toBeVisible();

    expect(el).toExist();
    expect(el).toBeInDOM();
    expect(el).toBeVisible();

    expect($('#testClickConfirm')).toExist();
    expect($('#testClickConfirm')).toBeInDOM();
    expect($('#testClickConfirm')).toBeVisible();

}));

1 个答案:

答案 0 :(得分:1)

据我所知,当测试依赖于浏览器来计算某些内容(例如元素的大小)时,您只需要将元素附加到DOM。如果不需要那么你可以把它留在“冷静”。

在需要元素位于DOM内部的情况下,使用编译版本大部分就足够了。我无法想到在编译它之前将“raw”元素附加到DOM会有用的任何场景。