12

In a unit test, how can I instantiate a custom element (or view) and get access to the live DOM element?

I read this article which gets to the point where the custom element is instantiated but I don't think I can get to the DOM element.

BTW, I know about Protractor and end-to-end testing but that's not what I'm looking for here.


Update Oct 14 2016:

I found out that I can register an instance like this to make the @inject(Element) work:

container = new Container().makeGlobal();
container.registerInstance(Element, document.createElement('div') );
vm = BehaviorInstance.createForUnitTest(Test, {}, {});

although the injection works (my Test custom element get the reference), that did not cause aurelia to do anything with the element. My custom element's template has not been used and therefore the element's innerHtml is <div></div>.

Jeremy Danyow
  • 26,470
  • 12
  • 87
  • 133
Sylvain
  • 19,099
  • 23
  • 96
  • 145
  • Check out Jasmine-JQuery, you can use setFixtures to create some UI: https://github.com/velesin/jasmine-jquery – Andrew Oct 19 '15 at 19:20
  • According to an Aurelia core team member, this is not supported yet. See https://github.com/aurelia/framework/issues/230. – Sylvain Oct 23 '15 at 03:51

1 Answers1

2

Edit 11/16/2015:

We're exploring ways to create integration tests that use actual DOM elements as we build out a more robust test suite for some of the built-in custom elements/attributes. Checkout the commits in this branch for more details.


Here's a unit test for a custom element: https://github.com/aurelia/templating/blob/master/test/behavior-testing.js#L57

To access the actual DOM element, use Aurelia's dependency injection container:

import {inject} from 'aurelia-framework';

@inject(Element)
export class MyViewModelOrCustomElementOrAttribute {
  constructor(element) {
    // use the element
    this.element = element;
  }
}

Unit test would have something like this:

let myvm =BehaviorInstance.createForUnitTest(MyViewModelOrCustomElementOrAttribute, attributesFromHTML, bindingContext);
let actualDomElement = myvm.element;
Community
  • 1
  • 1
Jeremy Danyow
  • 26,470
  • 12
  • 87
  • 133
  • Thanks. The unit test you pointed me to does not use `Element`. If I try to get `Element` injected as in your sample, I get an error when aurelia tries to instantiate an object of type `Element` by calling the `Element()` constructor during `BehaviorInstance.createForUnitTest()`. If I set a breakpoint at the first line of my test and execute `Element()` in the console, I get the same error as aurelia does : ` Uncaught TypeError: Illegal constructor`. – Sylvain Oct 10 '15 at 15:11
  • hmm - I think that's supposed to work- will do some research and get back to you. – Jeremy Danyow Oct 10 '15 at 21:19