Node.js assert断言原理与用法分析(2)

assert.throws( () => {}, Error ); //输出 AssertionError: Missing expected exception (Error).. assert.throws( () => {throw new Error('Wrong value');}, Error ); //输出 undefined assert.throws( () => {throw new Error('Wrong value');}, /Wrong/ ); //输出 undefined assert.throws( () => {throw new Error('Wrong value');}, /wrong/ ); //输出 Error: Wrong value assert.throws( () => {throw new Error('Wrong value');}, (err) => { if ((err instanceof Error) && /value/.test(err)) { return true; } }, 'unexpected error' ); //输出 undefined

Note that error can not be a string. If a string is provided as the second argument, then error is assumed to be omitted and the string will be used for message instead. This can lead to easy-to-miss mistakes:

注意:错误信息不能是一个字符串。如果字符串被作为第二个参数,那么错误就会被假定为省略,并且字符串将会被用作提示信息,这样很容易导致错误。

assert.throws(()=>{throw new Error('Wrong value');}, 'Wrong', 'did not throw with expected message'); //输出 undefined assert.throws(()=>{}, 'Wrong', 'did not throw with expected message'); //输出 AssertionError: Missing expected exception. Wrong assert.throws(()=>{}, /Wrong/, 'did not throw with expected message'); //输出 AssertionError: Missing expected exception. did not with expected message.

assert.ifError(value)

Throws value if value is truthy. This is useful when testing the error argument in callbacks.

当值为真时,抛出AssertionError错误。该方法在测试回调函数的参数时非常有用。

assert.ifError(0); //输出 undefined assert.ifError(1); //输出 1 assert.ifError('error'); //输出 error assert.ifError(new Error('there maybe wrong')); //输出 Error: there maybe wrong

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e5dd0f1ee96f6566ce30ef171e28e382.html