【问题标题】:Unit testing dynamically-rendered elements in Polymer在 Polymer 中对动态渲染元素进行单元测试
【发布时间】:2016-04-03 21:44:51
【问题描述】:

概述

dom-ifdom-repeat <templates> 中动态呈现的 DOM 元素似乎是异步呈现的,因此使单元测试有点痛苦。


聚合物成分

template(is='dom-if', if='{{!defaultPrintAll}}')
  template(is='dom-repeat', items='{{_pageBucketItems}}')
    button(type='button', class$='{{_computeDefaultClass(item)}}', on-tap='_togglePageClick') {{item}}

测试

  test("Clicking 'Export All' to off, reveals board-selection tiles", function() {
    $("#export-pdf-checkbox-all").siblings(".checkbox").trigger("click");
    Polymer.dom.flush()
    expect($(".board-range__button")).to.be.visible;
  });

为什么它似乎失败了:

单击触发dom-if/dom-repeat 的按钮时,元素不会以同步顺序呈现。

  • dom-if 和它的后续/嵌套 dom-repeat 异步渲染。

  • 更糟糕的是,button 本身以计算/绑定的方式获取它的类(请注意 button 上的 class$=)。

所以问题归结为:

在我模拟点击后是否可以强制渲染dom-ifdom-repeat和类的计算绑定以同步顺序激活所有这三个条件的按钮?


注意事项:

  • 我使用 Polymer 的官方 WCT 作为测试工具。
  • 我也在使用 chai-jquery。
  • 我也用过Polymer.dom.flush(),但还是不行,咳咳……冲洗。
  • 我知道我可以改用 chai-as-promised.js,但它会为我的测试增加不必要的复杂性,因为这样的小事,所以我想避免它。

【问题讨论】:

    标签: polymer polymer-1.0 chai wct


    【解决方案1】:

    不要使用Polymer.dom.flush(),而是尝试使用WCT 放在窗口上的flush 函数。理论上,这将在模板渲染后将要执行的回调函数排入队列。

    test("Clicking 'Export All' to off, reveals board-selection tiles", function(done) {
        $("#export-pdf-checkbox-all").siblings(".checkbox").trigger("click");
        flush(function () {
            expect($(".board-range__button")).to.be.visible;
            done();
        }
    });
    

    重要提示:异步测试需要将 done 函数传递到测试回调中,并且需要在评估条件后调用 done。

    【讨论】:

    • bingo - 谢谢,但这与在测试中使用 setTimeout() 有何不同?我如何能够继续依赖于此的下一个测试?
    • 自己看:github.com/Polymer/web-component-tester/blob/… 在大多数情况下,与仅使用 arg 为 0 的 setTimeout 相比没有真正的区别。但是,您想使用 window.flush 而不是 setTimeout 的原因是,是在未来版本的 web-component-tester 中,flush 的实现可能会变得更智能和/或更有用。
    • 就下一个测试而言,这些测试将不会被执行,直到前一个测试调用它的完成函数、断言失败或超时失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 2021-01-30
    相关资源
    最近更新 更多