【问题标题】:Assert.fail (node.js): what does Operator parameter mean?Assert.fail (node.js):Operator 参数是什么意思?
【发布时间】:2013-01-12 23:20:32
【问题描述】:

Node.js 单元测试模块有基本的断言assert.fail:

assert.fail(actual, expected, message, operator)

operator 是什么意思?我对单元测试真的很陌生...

【问题讨论】:

    标签: node.js unit-testing assert


    【解决方案1】:

    文档内容:operator 的值用于在提供错误消息时分隔 actualexpected 的值。这在 Node.js 的documentation for the assert module 中有描述。

    但是,如果您在交互式 shell 中尝试此操作,您会发现该参数似乎被忽略了:

    > assert.fail(23, 42, 'Malfunction in test.', '###')
    AssertionError: Malfunction in test.
        at repl:1:9
        at REPLServer.self.eval (repl.js:111:21)
        at Interface.<anonymous> (repl.js:250:12)
        at Interface.EventEmitter.emit (events.js:88:17)
        at Interface._onLine (readline.js:199:10)
        at Interface._line (readline.js:517:8)
        at Interface._ttyWrite (readline.js:735:14)
        at ReadStream.onkeypress (readline.js:98:10)
        at ReadStream.EventEmitter.emit (events.js:115:20)
        at emitKey (readline.js:1057:12)
    

    看看implementation of the assert module, lines 101-109,这一切都说得通:

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

    因此,更好的描述可能是它不会在消息中自动使用,但如果您捕获异常并自己创建适当的消息,则可以使用它 .因此,如果您要创建自己的测试框架,此参数可能会很有用。

    如果您省略 message 参数,您可以强制 Node.js 使用该参数,例如通过明确传递undefined

    > assert.fail(23, 42, undefined, '###')
    AssertionError: 23 ### 42
    [...]
    

    【讨论】:

    • 太好了,谢谢!实际上,文档中根本没有提到一个参数。我必须自己学会在源代码中找到这些函数 - 看起来文档可能比代码更令人困惑......
    • 基本上,您可以在 Node.js 存储库内的 lib 文件夹中找到所有库。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-07
    • 2016-10-17
    • 2015-03-05
    • 2014-05-31
    • 2012-09-16
    • 2020-12-16
    • 2017-04-13
    相关资源
    最近更新 更多