Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the DOM Element in an aurelia unit test?

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

like image 467
Sylvain Avatar asked Oct 09 '15 22:10

Sylvain


1 Answers

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;
like image 134
Jeremy Danyow Avatar answered Nov 15 '22 16:11

Jeremy Danyow