Fyodor Khruschov
Fyodor Khruschov

Reputation: 1717

Angular.js UNIT test directive

I'm trying to make a unit test for angular directive. So this is the code:

describe('Test', function () {

  var element,
      scope;

  // load the service's module
  beforeEach(module('app'));


  beforeEach(inject(function ($compile, $rootScope) {
    scope = $rootScope.$new();
    element = angular.element('<div id="wow"></div>');
    $compile(element)(scope);
    element.scope().$apply();
  }));

  it('should', function () {
    console.log(document.getElementById('wow'));
  });

});

I got null in the console.

Of course this is just a test case. In real code getElementById is used by plugin which is wrapped with my directive, which is I'm trying to test.

So my question is: why the DOM element which is just compiled not be found by getElementById. If this is correct behavior, how can I avoid this mistake.

Thanks

Upvotes: 0

Views: 609

Answers (2)

var-foo
var-foo

Reputation: 106

The DOM element isn't found because jasmine never actually attaches it to the DOM. If you want to get the element, just refer to it as element. For example:

it('should', function() {
  expect(element.attr('id')).toBe('wow');
});

You can attach the element to the DOM manually, but remember to remove it when you're done with your test (I use the afterEach blocks for this). Jasmine uses the same DOM for your entire test suite, so if you forget to remove an element, you could get false positives or other unexpected results in your tests from elements being in the DOM that you didn't expect to be there. In general, you shouldn't have to attach your element to the DOM unless you're testing certain interactions (blur works without attaching to the DOM, but focus doesn't, for example).

Upvotes: 1

javaCity
javaCity

Reputation: 4318

You need to append the element in the document somewhere. Here's working plnk.

Only thing thing that I added:

angular.element(document.body).append(element);

Upvotes: 2

Related Questions