为我的测试编写断言时,断言失败无法提供足够的信息,无需打开 IDE 并开始调试。
例如,我有一些使用“assert”库的代码:
import * as assert from 'assert'
// some code
assert(someObject.getValue() === 0)
我刚刚明白
AssertionError [ERR_ASSERTION]: false == true
+ expected - actual
-false
+true
这个错误消息并没有什么实际意义。作为解决方法,我将其添加到断言的消息中:
assert(someObject.getValue() === 0,
'\nActual: ' + someObject.getValue() +
'\nExpected: ' + 0)
是否有更好、更清晰的方法来仅显示预期值和实际值,而不覆盖每个断言的消息?我还尝试创建一个
assert
包装器,但我无法从表达式中提取实际值和预期值。
编辑:
assert.strictEqual
仅解决平等问题。但是一旦包含任何其他运算符,我们就会遇到同样的问题(例如 assert(someObject.getValue() > 0)
如有任何建议,我们将不胜感激。
谢谢!
您可以使用 AssertionError 来实现此目的,在调用 assert 时将其作为第二个参数传递。例如,我们要检查同义词数据是否与真实数据匹配:
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"
]
您可以使用 assert.strictEqual(actual, Expected[, message]) 来获取实际/预期的错误消息,而不需要第三个消息参数:
assert.strictEqual(someObject.getValue(), 0)
您会收到一条错误消息,例如:
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 0
希望有帮助!