Reputation: 63739
I want to write a custom assert
function for QUnit to check if an actual string matches an expected regex. With help of this question I wrote a first basic version that works as expected:
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");
});
This outputs:
Message: Expected: "string matching /gibberish/", Actual: "flower"
Great!
However, while writing this I checked both the QUnit.extend
docs and the QUnit.push docs. However, the latter mentions that:
This method is deprecated and it's recommended to use it through its direct reference in the assertion context.
But I fail to see how I can apply this advice inside the QUnit.extend
context.
How do I properly write a custom assertion that doesn't use the deprecated QUnit.push
function?
Upvotes: 9
Views: 569
Reputation: 63739
As suggested by @sirrocco in a comment, there's a different push
method document that you should be using for this: see this documentation link. This means your answer is as simple as changing one line of code to use this.push
instead of Qunit.push
:
this.push(success, actual, expected, message);
Here's a full working example:
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>
Upvotes: 2