我想为 QUnit 编写自定义 assert
函数来检查 actual 字符串是否与 expected 正则表达式匹配。在this question的帮助下我编写了第一个按预期工作的基本版本:
QUnit.extend(QUnit.assert, {
matches: function (actual, regex, message) {
var success = !!regex && !!actual && (new RegExp(regex)).test(actual);
var expected = "String matching /" + regex.toString() + "/";
QUnit.push(success, actual, expected, message);
}
});
QUnit.test("New assertion smoke test", function (assert) {
// force a failure to see the new assert work properly:
assert.matches("flower", "gibberish");
});
这个输出:
Message: Expected: "string matching /gibberish/", Actual: "flower"
太棒了!
然而,在写这篇文章时,我同时检查了 the QUnit.extend
docs和 the QUnit.push docs .然而,后者提到:
This method is deprecated and it's recommended to use it through its direct reference in the assertion context.
但我看不出如何在 QUnit.extend
上下文中应用此建议。
如何正确编写不使用已弃用的 QUnit.push
函数的自定义断言?
最佳答案
正如@sirrocco 在评论中所建议的,有一个不同的 push
方法文档,您应该为此使用它:参见this documentation link .这意味着您的答案就像更改一行代码以使用 this.push
而不是 Qunit.push
一样简单:
this.push(success, actual, expected, message);
这是一个完整的工作示例:
QUnit.extend(QUnit.assert, {
matches: function (actual, regex, message) {
var success = !!regex && !!actual && (new RegExp(regex)).test(actual);
var expected = "String matching /" + regex.toString() + "/";
this.push(success, actual, expected, message);
}
});
QUnit.test("New assertion smoke test", function (assert) {
// force a failure to see the new assert work properly:
assert.matches("flower", /.*our.*/, "Wanted regex to match!");
});
<script src="https://code.jquery.com/qunit/qunit-1.20.0.js"></script>
<link href="https://code.jquery.com/qunit/qunit-1.20.0.css" rel="stylesheet"/>
<div id="qunit"></div>
关于javascript - 如何在不使用 QUnit.push 的情况下为 QUnit 编写新的断言函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277884/