Pregunta

When I set up tests using just compile and link, the directive is triggered but the element only exists in limbo because the tests below fail if I do not explicitly add it to the DOM.

I am simply wondering whether I should be adding the precompiled angular.element(...) to the DOM or the compiled/linked linkFr(scope) or if I am going about this all wrong.

Test Setup

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);

}));

Tests

As long as I call either $('body').append(el); or $('body').append(element); all tests pass, otherwise they all fail.

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();

}));
¿Fue útil?

Solución

To the best of my knowledge you only need to append the element to the DOM when your test relies on the browser to compute something (e.g. the size of an element). If that's not required then you can leave it in "limbo".

In the cases you need the element to be inside the DOM, using the compiled version will mostly suffice. I can't think of any scenario where appending the "raw" element to the DOM before compiling it would be useful.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top