Node.js中定义的AssertionError在哪里?

我希望我的unit testing断言特定的函数调用会在需要时抛出一个AssertionError,而不是抛出一个exception。 assertion库(expect)通过传入一个exception构造函数来支持这样的事情,但是我似乎无法findAssertionError构造函数被导出的地方。 它只是为了成为一个内部阶级,而不是暴露给我们? 文档包含大量的参考,但没有链接。

我有一个超级哈克的方式:

let AssertionError; try { const assert = require("assert"); assert.fail(); } catch (ex) { AssertionError = ex.constructor; } 

但我希望有更好的方法。

经过在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); } } 

断言错误类是在这里定义的:

 assert.AssertionError 

*testing和AsserionError预期的结果可能是有用的:

 assert.throws( FunctionThatShouldThrow_AssertionError, assert.AssertionError ) 
Interesting Posts