NodeJS 显示Assert失败的预期值和实际值

ncgqoxb0  于 12个月前  发布在  Node.js
关注(0)|答案(2)|浏览(95)

在为我的测试编写Assert时,如果不打开IDE并开始调试,Assert失败就无法提供足够的信息。
例如,我有一些使用'assert'库的代码:

import * as assert from 'assert'

// some code

assert(someObject.getValue() === 0)

我只是得到

AssertionError [ERR_ASSERTION]: false == true
           + expected - actual

           -false
           +true

此错误消息实际上没有意义。作为一种变通方法,我在Assert的消息中添加了它:

assert(someObject.getValue() === 0, 
       '\nActual: ' + someObject.getValue() + 
       '\nExpected: ' + 0)

有没有更好、更干净的方法来显示预期值和实际值,而不覆盖每个Assert上的消息?我还尝试创建一个assert Package 器,但无法从表达式中提取实际值和预期值。
编辑:assert.strictEqual解决了这个问题的平等只。但是,一旦任何其他运营商被包括在内,那么我们有同样的问题(例如,assert(someObject.getValue() > 0)
任何建议将不胜感激。
谢谢你,谢谢

1hdlvixo

1hdlvixo1#

您可以使用AssertionError来实现这一点,在调用assert时将其作为第二个参数传递。例如,我们想检查synon数据是否与真实的数据匹配:

const test = {
        trigger: (event, data) => { }
    };
    const spy = sinon.spy(test, 'trigger');

    test.trigger('event', 'data1'); // with invalid data to cause an error

    assert(spy.calledWithExactly('event', 'data2'), new AssertionError({
        message: 'trigger should be called with the proper arguments',
        actual: spy.getCalls()[0].args,
        expected: ['event', 'data2']
    }));

这将抛出一个错误:

AssertionError [ERR_ASSERTION]: trigger should be called with the proper arguments
  + expected - actual

   [
     "event"
  -  "data1"
  +  "data2"
   ]
nbysray5

nbysray52#

你可以使用assert.strictEqual(actual,expected[,message])来获取实际的/预期的错误消息,而不需要第三个消息参数:

assert.strictEqual(someObject.getValue(), 0)

你会得到一个错误消息,如:

// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 0

希望这有帮助!

相关问题