javascript - 与 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 返回错误吗?
解决方案
这不是测试。在您发布的图片中,您有:
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
.
推荐阅读
- r - 加载 ggplot2 时抛出错误:包或命名空间加载失败 .... 没有名为“颜色空间”的包
- spring - 经过身份验证的用户的 Spring 安全过滤器
- libreoffice - 在单元格 B1 中使用 A1 的部分值来计算公式
- c++ - 当实例为右值时,成员函数的具体实现?
- java - 当我尝试添加到 ArrayList 时,我得到 NullPointerException
- python - python3和pip安装在mac上但是找不到pip3命令
- sql - 如何将一些数据连接到所有数据
- python - 如何在熊猫 df 中每隔一行创建新列
- reactjs - React Lifecycles 管理具有变化值的间隔
- sparql - 维基数据按人口对给定州的城市进行排序