Tur*_*yes 5 unit-testing node.js assertion expect.js
我想让我的单元测试断言特定的函数调用会在预期时抛出 AssertionError,而不是根本抛出异常。断言库(expect)通过传入异常构造函数来支持这样的事情,但我似乎无法找到导出 AssertionError 构造函数的位置(如果有的话)。它是否只是一个内部类而不暴露给我们?该文档包含对其的大量引用,但没有链接。
我有一个超级hacky的方法:
let AssertionError;
try {
const assert = require("assert");
assert.fail();
}
catch (ex) {
AssertionError = ex.constructor;
}
Run Code Online (Sandbox Code Playgroud)
但我希望有更好的方法。
在对 Nodejs github 存储库进行研究之后,我可以告诉你它在这里: https: //github.com/nodejs/node/blob/c75f87cc4c8d3699e081d37bb5bf47a70d830fdb/lib/internal/errors.js
AssertionError 定义如下:
class AssertionError extends Error {
constructor(options) {
if (typeof options !== 'object' || options === null) {
throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
}
var { actual, expected, message, operator, stackStartFunction } = options;
if (message) {
super(message);
} else {
if (actual && actual.stack && actual instanceof Error)
actual = `${actual.name}: ${actual.message}`;
if (expected && expected.stack && expected instanceof Error)
expected = `${expected.name}: ${expected.message}`;
if (util === null) util = require('util');
super(`${util.inspect(actual).slice(0, 128)} ` +
`${operator} ${util.inspect(expected).slice(0, 128)}`);
}
this.generatedMessage = !message;
this.name = 'AssertionError [ERR_ASSERTION]';
this.code = 'ERR_ASSERTION';
this.actual = actual;
this.expected = expected;
this.operator = operator;
Error.captureStackTrace(this, stackStartFunction);
}
}Run Code Online (Sandbox Code Playgroud)
如果我是你,我不会重新定义 AssertionError,那是非常非常 hacky 的。我认为最好的选择是将该类扩展为 MyAssertionError 或创建一个扩展错误的孪生类。
希望有帮助!
| 归档时间: |
|
| 查看次数: |
5364 次 |
| 最近记录: |