模拟InnerHTML输出文本Javascript

问题描述 投票:0回答:1

我正在做一个项目,我们正在构建一个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);

// controller-tests.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功能?

javascript html unit-testing mocking getelementbyid
1个回答
0
投票

谢谢西德尼的建议。这就是我想出来通过考试的原因;

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页面。

© www.soinside.com 2019 - 2024. All rights reserved.