【问题标题】:JS unit tests without having to copy the whole HTML into the unit test?JS 单元测试无需将整个 HTML 复制到单元测试中?
【发布时间】:2014-04-18 00:04:26
【问题描述】:

我正在为每个函数编写 JS 单元测试的项目中工作。假设你有 JS 代码为页面做一些事情,比如:

myProject.myPage.onDomReady = function() {
  $("#something").on("click", this.doSomething);
  $("#something-else").on("click", this.doSomethingElse);
}

在单元测试中,项目中的标准做法是将页面的html复制/粘贴到js测试中。喜欢:

module("pages/my_page_test.js", {
  setup: function() {
    this.myPage = Unit.fixture('\
      <div class="container" id="my-form-container" style="display: block;">\
        <div class="container-bg"></div>\
        <div class="container-box" style="width:250px">\
        <div class="container-title">\
          <span class="container-title-text">Engage?</span>\
        </div>\
      </div>\
    ');
  }
);

通常它的行数比这多得多。

我的问题是:这是为页面功能编写 JS 单元测试的好方法吗?我的意思是你最终将大部分 HTML 页面复制到你的 JS 中只是为了测试。并且每次更改 HTML 时,理论上您也应该在测试中更新 HTML。

有没有更好的办法?

【问题讨论】:

标签: javascript html unit-testing qunit


【解决方案1】:

使用以下方法之一:

  • 通过 DOM 引用 HTML:

    var foo = Unit.fixture(document.getElementById("foo").outerHTML)
    
  • 通过the jQuery constructor生成标记

    var foo = Unit.fixture($("<span/>", {"class":"foo", "id":"bar", "html": "<span/>"}).get(0).outerHTML )
    
  • 通过strings with Unicode escapes生成标记

    var foo = Unit.fixture("<label><input type=|radio| name=|bar| value=|baz|>bop</label>").replace(/\|/g,"\u0022")
    

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2010-10-22
    • 2022-01-06
    • 2017-04-06
    相关资源
    最近更新 更多