代码之家  ›  专栏  ›  技术社区  ›  Doug

设置断言的自定义错误消息(node.js)

  •  0
  • Doug  · 技术社区  · 6 年前

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

    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
    

    我道歉,我知道我应该包括“到目前为止我所做的”,但到目前为止我所做的一切都没有影响。同样,我在节点文档中丢失了:)

    2 回复  |  直到 6 年前
        1
  •  2
  •   Adelin    6 年前

    你不能不篡改3 研发 自由党 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 把你自己归档,这样,除了触发通常的事情,它还可以做你想要的。

      虽然很快, 这将永远导致一个破碎的依赖。

    3. 查找其他断言库(如果有适合您需要的断言库)

        2
  •  0
  •   Erick Ribeiro    6 年前

    我的答案

    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