Monday, April 28, 2014

Dynamic Polymer Definition BeforeEach

I swore I wouldn't do this again…

I am now able to dynamically define a Polymer custom element (the actual definition, not just using one) on a regular page and in the setup for my Karma / Jasmine test suite. But… can I dynamically define an element before each test, not just before the entire test suite runs?

After last night, I have this working before all tests thanks to a cleverly placed onload:
var script = document.createElement("script");
script.src = "/base/bower_components/platform/platform.js";
script.onload = defineTestPolymerElements;

var link = document.createElement("link");
link.rel = 'import';
link.href = "/base/bower_components/polymer/polymer.html";
The defineTestPolymerElements() function assembles the Polymer definition from a judicious combination of document.createElement() and innerHTML. What that does is, as soon as the Polymer's polyfill platform loads, adds the dynamically generated <polymer-element> definition to the page. That would occur before the Polymer library itself is loaded because that will not happen until the platform library loads, extending the normal <link> tag to also import custom HTML.

But what happens if I remove the onload and add the definition to the page after the Polymer library loads? To find out, I comment out the script.onload assignment from the “before all” setup. Then, inside the describe() block of my test, I add the beforeEach() to do the same dynamic Polymer element definition:
describe('Double binding', function(){
  // Other setup...
  // Tests go here...
When I run that, my test fails:
Expected null to equal '84'.
Error: Expected null to equal '84'.
    at new jasmine.ExpectationResult 
The Polymer definition is created in the DOM as desired:

Console log statements added inside the definition's <script> tag are even evaluated. But the <x-double> element that ought to be defined is still seen as an HTMLUndefinedElement.

After digging through the Polymer source and the associated platform code, I have to confess that I am stumped. The registration process of Polymer elements seems to work through a queue, but if I check that queue under debug, it seems as though the element is no longer in the queue. I would think that meant that the element was defined, but, obviously I am not seeing that.

I am curious enough about this that I will likely give it one more try tomorrow, but after that, I need to cut my losses and move on.

Day #48

No comments:

Post a Comment