assert.fail(actual, expected[, message[, operator[, stackStartFn]]])


稳定性: 0 - 弃用: 改为使用 assert.fail([message]) 或其他 assert 函数。

如果 message 为假,则错误消息设置为由提供的 operator 分隔的 actualexpected 的值。 如果只提供了两个 actualexpected 参数,则 operator 将默认为 '!='。 如果 message 作为第三个参数提供,则它将用作错误消息,其他参数将作为抛出对象的属性存储。 如果提供了 stackStartFn,则该函数之上的所有堆栈帧都将从堆栈跟踪中删除(参见 Error.captureStackTrace)。 如果没有给出参数,则将使用默认消息 Failed

const assert = require('assert').strict;

assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'

assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2

assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail

assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops

assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array

在后三种情况下,actualexpectedoperator 对错误消息没有影响。

使用 stackStartFn 截断异常堆栈跟踪的示例:

function suppressFrame() {
  assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
//     at repl:1:1
//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
//     ...

Stability: 0 - Deprecated: Use assert.fail([message]) or other assert functions instead.

If message is falsy, the error message is set as the values of actual and expected separated by the provided operator. If just the two actual and expected arguments are provided, operator will default to '!='. If message is provided as third argument it will be used as the error message and the other arguments will be stored as properties on the thrown object. If stackStartFn is provided, all stack frames above that function will be removed from stacktrace (see Error.captureStackTrace). If no arguments are given, the default message Failed will be used.

const assert = require('assert').strict;

assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'

assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2

assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail

assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops

assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array

In the last three cases actual, expected, and operator have no influence on the error message.

Example use of stackStartFn for truncating the exception's stacktrace:

function suppressFrame() {
  assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
//     at repl:1:1
//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
//     ...