为断言设置自定义错误消息 (Node.js)

Set Custom Error Message for Assert (Node.js)

我迷失在 Node 文档中,我很难弄清楚如何为我的所有 assert 语句创建自定义(或修改现有的)错误处理,而不必在每个 assert 语句中包含单独的消息断言。

const assert = require('assert');

describe('Test 1', function(){
  describe('Checks State', function(){
    it('will fail', function(){
        assert.strictEqual(true, false);
    });
  });
});

正如预期的那样,前面的代码只会生成如下内容:

1) "Test 1 Checks State will fail"
true === false

我是 运行 WebDriverIO,我的目标是在错误消息中包含 browser.sessionId 不必手动填写第三个 (消息)参数在每个测试中。

assert.strictEqual(true, false, browser.sessionId);

如果我能生成如下错误消息,那就太理想了:

1) "Test 1 Checks State will fail"
abc012-efg345-hij678-klm901
true !== false

抱歉,我知道我应该包括 "what I have done so far" -- 但到目前为止我所做的一切都没有任何影响。再一次,我在节点文档中迷路了:)

你不能,如果不篡改第 3rd 方库 assert

在幕后,使用 fail 函数,该函数在 assert 上下文中是私有的,您不能告诉 assert 使用自定义 fail 函数。

这是幕后使用的函数:

function fail(actual, expected, message, operator, stackStartFunction) {
  throw new assert.AssertionError({
    message: message,
    actual: actual,
    expected: expected,
    operator: operator,
    stackStartFunction: stackStartFunction
  });
}

因此,您有三个选择:

  1. (推荐)Fork the lib on github。实施一些观察者,如 onFail 或允许它可扩展并创建拉取请求。

  2. (不推荐) 自己覆盖 node_modules\assert\assert.js 文件中的 fail 函数,这样,除了触发通常的东西外,它也能满足您的需求。

    虽然很快,但这将导致永远中断依赖关系。

  3. 寻找其他断言库(如果有满足您需要的)

我的回答

const assert = require('assert');
describe('Set Custom Error Message for Assert (Node.js)', () => {
    it('Message Assert', () => {
       assert.fail(21, 42, 'This is a message custom', '##');
    });
});

Reference