JS单元测试,而不必将整个HTML复制到单元测试中

JS unit tests without having to copy the whole HTML into the unit test?

本文关键字:单元测试 HTML 复制 不必 JS      更新时间:2023-09-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。

有更好的方法吗?

使用以下方法之一:

  • 通过DOM:引用HTML

    var foo = Unit.fixture(document.getElementById("foo").outerHTML)
    
  • 通过jQuery构造函数生成标记

    var foo = Unit.fixture($("<span/>", {"class":"foo", "id":"bar", "html": "<span/>"}).get(0).outerHTML )
    
  • 通过带有Unicode转义的字符串生成标记

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