【问题标题】:How to get assert to print a success message?如何让断言打印成功消息?
【发布时间】:2013-06-17 19:02:26
【问题描述】:

这是我写的一个断言

assert.equal(0,0,"Test Passed);

我希望它会打印消息测试通过,但它没有发生。但是,如果断言失败,则消息将与错误一起显示。

那么如果测试成功,有什么办法可以打印消息呢?

【问题讨论】:

    标签: node.js unit-testing


    【解决方案1】:

    根据来源,只有在断言失败时才打印消息。

    assert.equal = function equal(actual, expected, message) {
      if (actual != expected) fail(actual, expected, message, '==', assert.equal);
    };
    

    为了完整起见,这里是fail的定义。

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

    【讨论】:

    • so.....如果测试成功,有没有办法发消息?
    【解决方案2】:

    没有显示成功消息的内置功能。然而,因为 assert 在失败时会抛出错误(并且执行停止),所以在 assert 调用之后立即放置成功消息可以有效地实现同样的效果:

    const assert = require('assert')
    
    assert.deepStrictEqual(value, otherValue)
    console.log('test passed') // unreachable if assert fails as it throws an error
    

    如果要继续执行,可以使用try/catch

    const tests = [
      [0,1],
      [1,1],
    ]
    
    for (const [value, otherValue] of tests) {
      try {
        assert.deepStrictEqual(value, otherValue)
        console.log(`Success: ${value} equals ${otherValue}`)
      } catch(error) {
        console.error(`Failure: ${value} does not equal ${otherValue}`)
      }
    }
    
    // output:
    // Failure: 0 does not equal 1
    // Success: 1 equals 1
    

    请注意,如果将其用于自动化测试,失败时所需的结果可能仍然是抛出错误或exit 1 让环境知道测试失败。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2016-12-18
      相关资源
      最近更新 更多