How to add custom assertions in Nodeunit

2019-04-09 17:50发布

问题:

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();
}

回答1:

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();
    }
});