assert.throws()函数详解

assert.throws(block[, error][, message])

期望 block 函数抛出一个错误。
如果指定 error,它可以是一个构造函数、正则表达式或验证函数。
如果指定 message,如果 block 因为失败而抛出错误,message 会是由 AssertionError 提供的值。
验证使用构造函数实例:

assert.throws(
    () => {
        throw new Error('Wrong value');
    },
    Error
);

使用 RegExp 验证错误信息:

assert.throws(
    () => {
        throw new Error('Wrong value');
    },
    /value/
);

自定义错误验证:

assert.throws(
    () => {
        throw new Error('Wrong value');
    },
    function (err) {
        if ((err instanceof Error) && /value/.test(err)) {
            return true;
        }
    },
    'unexpected error'
);

请注意,Error 不能是字符串。如果字符串是作为第二个参数,那么 error 会被假定省略,字符串将会使用 message 替代。这很容易导致丢失错误:

// THIS IS A MISTAKE! DO NOT DO THIS!
assert.throws(myFunction, 'missing foo', 'did not throw with expected message');

// Do this instead.
assert.throws(myFunction, /missing foo/, 'did not throw with expected message');

猜你喜欢

转载自www.cnblogs.com/lalalagq/p/9908405.html