busterjs / buster

Abandoned - A powerful suite of automated test tools for JavaScript.
http://docs.busterjs.org
Other
448 stars 37 forks source link

Match if object has properties #430

Closed gxxcastillo closed 9 years ago

gxxcastillo commented 9 years ago

I'd like to test if an object has certain properties but I don't care what the property values are. What's the best way to do this?

Currently, I'm passing a function matcher into my assertion and manually checking for the existence of each property:

function (value) {
     return value.hasOwn('prop1') && value.hasOwn('prop2') && value.hasOwn('prop3');
}

Would be great if there was something like .hasProperties() where you pass it an array of property names and it passes if the object has those properties.

dwittner commented 9 years ago

Buster.JS provides a way to add custom assertions. In your case the custom assertion could look like this:

var buster = require("buster"),
    assert = buster.assert,
    refute = buster.refute;

buster.testCase("hasProperties", {

    "test new assertion": function () {
        buster.referee.add("hasProperties", {
            assert: function (actual, properties) {
                var i;
                for (i = 0; i < properties.length; i++) {
                    if (!actual.hasOwnProperty(properties[i])) {
                        this.prop = properties[i];
                        return false;
                    } 
                }
                return true;
            },
            refute: function (actual, properties) {
                var i;
                for (i = 0; i < properties.length; i++) {
                    if (actual.hasOwnProperty(properties[i])) {
                        this.prop = properties[i];
                        return false;
                    } 
                }
                return true;
            },
            assertMessage: "Expected ${0} to have property ${prop}!",
            refuteMessage: "Expected not to have property ${prop}!",
            expectation: "toHasProperties"
        });

        var obj = {
            prop1: "val1",
            prop2: "val2",
            prop3: "val3",
            prop4: "val4"
        };

        assert.hasProperties(obj, ["prop1", "prop2"]);
        refute.hasProperties(obj, ["prop7"]);
    }
});

If you omit method refute, Buster.JS uses !assert as the refutation result.

dwittner commented 9 years ago

@uglymunky, are you satisfied with the answer?

gxxcastillo commented 9 years ago

yep, thank you :)