聚合物单元测试模拟依赖性

ses*_*eva 7 unit-testing polymer

我刚刚开始使用聚合物.我试图单元测试一个具有依赖关系的自定义元素,我想伪造/嘲笑这些.我找到了Scott Miles关于如何模拟core-ajax实现的建议.我认为我可以轻松地遵循该模式,但这只有在我的元素不导入要模拟的东西(在本例中为core-ajax)元素时才有效.如果它确实导入它,那么当测试试图运行时我得到

'未捕获NotSupportedError:无法在'Document'上执行'registerElement':类型'core-ajax'的注册失败.具有该名称的类型已经注册.

如果我可以做一些像document.unregister核心-ajax元素并在我的测试中再次导入它,我会更开心!聚合物很棒但是如果我不能对其进行单元测试,那么它会带来很大的风险(至少在构建需要维护/更改的应用程序时)

你们是怎么解决这个问题的?我一直在深入研究Polymer和PolymerLab元素的回购,其中大多数缺乏测试.到目前为止,我没有找到很多关于如何做的参考.

谢谢您的帮助!

圣地亚哥

Scotts的建议是:

而不是导入core-ajax/core-ajax.html,创建自己的core-ajax元素.

<polymer-element name="core-ajax" attributes="response">
<script>
  Polymer('core-ajax', {
    attached: function() {
      this.response = ['a', 'b', 'c'];
    }
 });
</script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)

显然,这只是一个例子,实际的实现取决于所需的模拟行为.

这只是解决问题的一种方法,还有很多其他方法.我很想知道你找到了什么(方便).

Cai*_*son -1

您可以尝试使用 js 命令式注册它,或者扩展您正在测试的每个元素并覆盖您想要模拟的属性或方法。我认为仅此而已。这就像我的谷歌地图自定义元素,我导入谷歌地图并更改周围的内容,如下所示:

<polymer-element name="core-gmaps" attributes="lat long mapzoom markerlat markerlong markertitle" extends="google-map">
    <template>
        <style>
        :host{
            width: 100%;
        }
        #vivaMap {
            display: block;
            height: 100%;
            width: 100%;            
        }
        </style>
        <google-map id="vivaMap" latitude="0" longitude="0" zoom="18">
            <google-map-marker id="vivaMarker" title="" latitude="0" longitude=""></google-map-marker>
        </google-map>
    </template>
    <script>

  Polymer("core-gmaps",{
    ready: function(){

        var map = this.$.vivaMap;
        map.latitude = Number(this.getAttribute('lat'));
        map.longitude = Number(this.getAttribute('long'));
        map.zoom = Number(this.getAttribute('mapzoom'));

        var mapMarker = this.$.vivaMarker;
        mapMarker.latitude = Number(this.getAttribute('markerlat'));
        mapMarker.longitude = Number(this.getAttribute('markerlong'));
        mapMarker.title = this.getAttribute('markertitle');
        /*map.addEventListener('google-map-ready', function(e) {
            console.log('Map loaded!');
        });*/
    }
  });
  </script>
</polymer-element>
Run Code Online (Sandbox Code Playgroud)

我仍然不确定它在专业上是否值得(我可能最终不会使用它),但在智力上完全值得。学到了一些好东西。因为我正在扩展谷歌地图,所以它被注册一次且仅一次。

编辑:
在我的例子中,我使用了就绪事件,因为我无法在地图本身没有准备好的情况下对其进行操作。但您可以从生命周期方法中选择事件回调。
名单在这里
PS:是的,我没有使用数据绑定,因为我不能。谷歌地图 api 抱怨它是 NaN 所以我不得不转换它。