【问题标题】:Mocking InnerHTML output text Javascript模拟 InnerHTML 输出文本 Javascript
【发布时间】:2018-06-10 04:05:36
【问题描述】:

我目前正在做一个项目,我们在其中构建一个 Web 应用程序,并且只使用 vanilla javascript。我们面临着编写自己的测试框架,然后用它来测试应用程序的挑战。

我正在尝试测试我的控制器,以便它将正确的 InnerHTML 文本输出到我的 id 标签。

在执行此操作时,我使用模拟来隔离此测试。我在嘲笑我的构造函数参数,以及创建自定义标签和 ID,但我的 console.logs 似乎没有识别它。

// note-controller.js

(function(exports) {
  function NoteController(list, listView, tag) {
    this.list = list;
    this.listView = listView;
    this.tag = tag;
  }

  NoteController.prototype.getListView = function() {
    return this.listView.converted;
  };

  NoteController.prototype.outputHTML = function() {
    document.getElementById(this.tag).innerHTML = this.getListView();
  };

  exports.NoteController = NoteController;
})(this);

// 控制器测试.js

describe("#outputHTML", () => {
    var list = { text: "hello this is another note" };
    var listView = {
      converted: "<ul><li><div>hello this is another note</div></li></ul>"
    };
    var mockElement = document.createElement("div");
    mockElement.id = "mock";
    mockElement.innerHTML = "hello";
    var noteController = new NoteController(list, listView, "mock");

    console.log(mockElement); 
 // outputs <div id="mock">hello</div> 

    console.log(document.getElementById("mock"));
 // outputs null

    expect.isEqual(
      "outputs the note as HTML to the page",
      noteController.outputHTML(),
      "<ul><li><div>hello this is another note</div></li></ul>"
    );
  });

你知道为什么这个创建的标签在第二个 console.log 中没有被识别吗?

我知道这还不正确,但我只是想模拟document.getElementById 作为朝着正确方向迈出的一步。话虽如此,您认为这是测试我的outputHTML 功能的有效策略吗?

【问题讨论】:

  • mockElement 没有被添加到 DOM,所以document.getElementById 找不到它
  • 啊,有没有办法将它添加到 DOM 中?
  • 向 DOM 添加元素最常用的方法是appendChild。你肯定想阅读一些关于 JavaScript DOM 操作的教程。

标签: javascript html unit-testing mocking getelementbyid


【解决方案1】:

感谢西德尼的建议。这就是我想出的通过测试的方法;

describe("#outputHTML", () => {
    var list = { text: "hello this is another note" };
    var listView = {
      converted: "<ul><li><div>hello this is another note</div></li></ul>"
    };
    var body = document.getElementsByTagName("body");
    var mockElement = document.createElement("span");
    mockElement.id = "test";
    body.item(0).appendChild(mockElement);

    var noteController = new NoteController(list, listView, "test");

    expect.isEqual(
      "outputs the note as HTML to the page",
      noteController.outputHTML(),
      "<ul><li><div>hello this is another note</div></li></ul>"
    );

    body.item(0).removeChild(mockElement);
});

我设法创建了一个临时元素标签,我的函数可以识别它以通过测试。测试后我将其删除,因为它实际上将其应用于我创建的 specrunner 页面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2020-12-20
    • 2021-12-27
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    相关资源
    最近更新 更多