-->

Randomly failing polymer web component test

2019-07-03 01:48发布

问题:

Yet another attempt to marry Polymer with ES6 classes.

And it almost works except a wct test failing randomly on a polymer component with an imported es6 class (by systemjs). As far as I understand, this happens because the script, containing class definition, gets loaded after mocha executed the test. The polymer component consists of two parts - html and javascript (to compile latter to es5),

html:

<dom-module id="my-test">
   <template>hello</template>
   <script>
      System.import('elements/my-test.js');
   </script>
</dom-module>

javascript:

import {User} from 'elements/model/user.js';

Polymer({
 is: "my-test",

 method: function(){
   console.log("method, user="+this.val);
 },

 ready: function(){
   this.user= new User(); //this.user is randomly undefined
 }
});

This seems to work quite stable in the browser, at least when loaded from localhost. But the only thing which ‘fixes’ the test is delaying Polymer’s ready call:

Polymer.whenReady = function (f) {
   console.log("polymer ready");
   setTimeout(f, 100);// "fix"
   //f();
}

which means at some point all this will fail in browser too (maybe when serving not from the localhost).

I’m thinking about getting somehow to the system-register’s promises and making something similar to HTMLImports.whenDocumentReady, but I still don’t have clear understanding of how all this works.

So any ideas and suggestions are highly appreciated!

The sample app is on github:

git clone https://github.com/bushuyev/test_test.git
cd test_test
git checkout tags/random_fail
npm install
bower install
gulp wct

To make it succeed more often than fail - change verbose to true in wct.conf.js.

kind of update: How to import system js SFX library

回答1:

It's possible to use Polymer, SystemJS and TypeScript (like ES6 but with added Polymer-friendly syntax) together in a very nice way, also handling HTML imports using SystemJS. That does involve a timing issue, and I've published a small shim that first waits from webcomponents.js to load and catches its ready event (before other code gets a chance to see it), then it loads Polymer and finally all other components and TypeScript code. Then it dispatches the event again so Polymer finishes initializing itself.

Here's an article about combining the technologies with the mentioned solution, downloadable code and a demo.