首页 > 解决方案 > 与 js bin 相比,Mocha 测试返回不同的答案

问题描述

我正在编写一个函数来尝试<noscript>从 html 字符串中删除标签。

我在下面写了我的函数:

function removeNoScript(str){
    var start = str.search("<noscript>");
    var end = str.search("</noscript>") + "</noscript>".length;

    var result = str.replace(str.substring(start,end),"");
    return result;
}

let result = removeNoScript("<p>first word</p><noscript>This shows up</noscript><p>second word</p>");

console.log(result)

这工作得很好,但是当我使用 chai 和 mocha 对此进行单元测试时(如下):

it("removes <noscript> in-between markup", () => {
    removeScripts(
      "<p>first word</p><noscript>This shows up</noscript><p>second word</p>"
    ).should.equal("<p>first word</p><p>second word</p>");
  });

我收到这个结果: 在此处输入图像描述

相同的功能在 JSBin 中有效,我注销了响应 - 知道为什么它在 JSBin 上有效,但 Mocha/Chai 返回错误吗?

PS:如果有帮助,这是我在编辑器中编写的代码的快照(忽略关于的评论,<script>因为我打算接下来删除它): 在此处输入图像描述

标签: javascriptnode.jsstringmocha.jschai

解决方案


这不是测试。在您发布的图片中,您有:

result = str.replace(str.substr(start, end),"");

使用substr而不是substring. 的第二个参数substr表示要提取的字符数,而第二个参数substring是要排除的第一个字符的索引。

substr:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

子字符串:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring

由于substr是遗产,您可能会想要坚持使用substring.


推荐阅读