How to write new assertion functions for QUnit without using QUnit.push?
Asked Answered
M

1

9

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?

Manthei answered 22/10, 2015 at 9:37 Comment(4)
Isn't this: api.qunitjs.com/push what you're looking after? There's an example at the bottomTyphoon
@Typhoon Yes, it actually looks like it. Will have to give it a go to be sure. If it is, I should probably also suggest a fix to QUnit's docs, would be nice if the deprecated push article (the one I link to in my question) links to the new one you suggested.Manthei
@Typhoon I got around to trying your suggestion, and it works: thank you! If you want to you can duplicate my answer, and I will delete my own and award you the well-deserved bounty.Manthei
No worries @Jeroen, glad we got it sortedTyphoon
M
2

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>
Manthei answered 30/10, 2015 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.