Search code examples
testingnode.jsnodeunit

How to add custom assertions in Nodeunit


Is there a way of adding custom assertions to the NodeUnit test object that gets passed to each test?

I'd like to do something like:

var Test = require('nodeunit').Test;

Test.prototype.customAssertion = function(obj) {
  test.same(obj.foo, 'bar');
  test.same(obj.bar, 'baz');
}

exports.test = function(test) {
  test.customAssertion(obj);

  test.done();
}

Solution

  • var assert = require('nodeunit').assert;
    var testCase = require('nodeunit').testCase;
    
    assert.isVowel = function(letter, message) {
        var vowels = [ 'a', 'e', 'i', 'o', 'u' ];
    
        if (vowels.indexOf(letter) == -1) {
            assert.fail(letter, vowels.toString(), message, 'is not in');
        }
    };
    
    exports["Vowel"] = testCase({
        "e should be a vowel": function(test) {
            test.isVowel("e", 'It should be a vowel.');
            test.done();
        }
    });