0

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

2
  • 2
    Is element appended to document? I think you need to do it yourself Commented May 6, 2014 at 18:34
  • But where the element placed If I not append it manually? Commented May 7, 2014 at 10:59

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

This is a more appropriate answer. If you have to attach something to the DOM then do it in an E2E test not a unit test.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.