assert.throws(fn[, error][, message])
版本历史
| 版本 | 变更 |
|---|---|
| v10.2.0 | The |
| v9.9.0 | The |
| v4.2.0 | The |
| v0.1.21 | 新增于: v0.1.21 |
fn<Function>error<RegExp> | <Function> | <Object> | <Error>message<string>
期望函数 fn 抛出一个错误。
🌐 Expects the function fn to throw an error.
如果指定,error 可以是 Class、<RegExp>、一个验证函数、一个验证对象(其中每个属性将进行严格的深度相等性检查),或者一个错误实例(其中每个属性都将进行严格的深度相等性检查,包括不可枚举的 message 和 name 属性)。在使用对象时,也可以在验证字符串属性时使用正则表达式。示例如下。
🌐 If specified, error can be a Class, <RegExp>, a validation function,
a validation object where each property will be tested for strict deep equality,
or an instance of error where each property will be tested for strict deep
equality including the non-enumerable message and name properties. When
using an object, it is also possible to use a regular expression, when
validating against a string property. See below for examples.
如果指定,message 将会被附加到 AssertionError 提供的消息中,当 fn 调用未抛出异常或在错误验证失败时。
🌐 If specified, message will be appended to the message provided by the
AssertionError if the fn call fails to throw or in case the error validation
fails.
自定义验证对象/错误实例:
🌐 Custom validation object/error instance:
import assert from 'node:assert/strict'; const err = new TypeError('Wrong value'); err.code = 404; err.foo = 'bar'; err.info = { nested: true, baz: 'text', }; err.reg = /abc/i; assert.throws( () => { throw err; }, { name: 'TypeError', message: 'Wrong value', info: { nested: true, baz: 'text', }, // Only properties on the validation object will be tested for. // Using nested objects requires all properties to be present. Otherwise // the validation is going to fail. }, ); // Using regular expressions to validate error properties: assert.throws( () => { throw err; }, { // The `name` and `message` properties are strings and using regular // expressions on those will match against the string. If they fail, an // error is thrown. name: /^TypeError$/, message: /Wrong/, foo: 'bar', info: { nested: true, // It is not possible to use regular expressions for nested properties! baz: 'text', }, // The `reg` property contains a regular expression and only if the // validation object contains an identical regular expression, it is going // to pass. reg: /abc/i, }, ); // Fails due to the different `message` and `name` properties: assert.throws( () => { const otherErr = new Error('Not found'); // Copy all enumerable properties from `err` to `otherErr`. for (const [key, value] of Object.entries(err)) { otherErr[key] = value; } throw otherErr; }, // The error's `message` and `name` properties will also be checked when using // an error as validation object. err, );const assert = require('node:assert/strict'); const err = new TypeError('Wrong value'); err.code = 404; err.foo = 'bar'; err.info = { nested: true, baz: 'text', }; err.reg = /abc/i; assert.throws( () => { throw err; }, { name: 'TypeError', message: 'Wrong value', info: { nested: true, baz: 'text', }, // Only properties on the validation object will be tested for. // Using nested objects requires all properties to be present. Otherwise // the validation is going to fail. }, ); // Using regular expressions to validate error properties: assert.throws( () => { throw err; }, { // The `name` and `message` properties are strings and using regular // expressions on those will match against the string. If they fail, an // error is thrown. name: /^TypeError$/, message: /Wrong/, foo: 'bar', info: { nested: true, // It is not possible to use regular expressions for nested properties! baz: 'text', }, // The `reg` property contains a regular expression and only if the // validation object contains an identical regular expression, it is going // to pass. reg: /abc/i, }, ); // Fails due to the different `message` and `name` properties: assert.throws( () => { const otherErr = new Error('Not found'); // Copy all enumerable properties from `err` to `otherErr`. for (const [key, value] of Object.entries(err)) { otherErr[key] = value; } throw otherErr; }, // The error's `message` and `name` properties will also be checked when using // an error as validation object. err, );
使用构造函数验证 instanceof:
🌐 Validate instanceof using constructor:
import assert from 'node:assert/strict'; assert.throws( () => { throw new Error('Wrong value'); }, Error, );const assert = require('node:assert/strict'); assert.throws( () => { throw new Error('Wrong value'); }, Error, );
使用 <RegExp> 验证错误消息:
🌐 Validate error message using <RegExp>:
使用正则表达式会对错误对象运行 .toString,因此也会包含错误名称。
🌐 Using a regular expression runs .toString on the error object, and will
therefore also include the error name.
import assert from 'node:assert/strict'; assert.throws( () => { throw new Error('Wrong value'); }, /^Error: Wrong value$/, );const assert = require('node:assert/strict'); assert.throws( () => { throw new Error('Wrong value'); }, /^Error: Wrong value$/, );
自定义错误验证:
🌐 Custom error validation:
该函数必须返回 true 以表示所有内部验证通过。否则将以 AssertionError 失败。
🌐 The function must return true to indicate all internal validations passed.
It will otherwise fail with an AssertionError.
import assert from 'node:assert/strict'; assert.throws( () => { throw new Error('Wrong value'); }, (err) => { assert(err instanceof Error); assert(/value/.test(err)); // Avoid returning anything from validation functions besides `true`. // Otherwise, it's not clear what part of the validation failed. Instead, // throw an error about the specific validation that failed (as done in this // example) and add as much helpful debugging information to that error as // possible. return true; }, 'unexpected error', );const assert = require('node:assert/strict'); assert.throws( () => { throw new Error('Wrong value'); }, (err) => { assert(err instanceof Error); assert(/value/.test(err)); // Avoid returning anything from validation functions besides `true`. // Otherwise, it's not clear what part of the validation failed. Instead, // throw an error about the specific validation that failed (as done in this // example) and add as much helpful debugging information to that error as // possible. return true; }, 'unexpected error', );
error 不能是字符串。如果第二个参数提供的是字符串,则假定省略了 error,该字符串将用于 message。这可能会导致容易被忽略的错误。使用与抛出的错误消息相同的消息将导致 ERR_AMBIGUOUS_ARGUMENT 错误。如果将字符串作为第二个参数,请仔细读取下面的示例:
import assert from 'node:assert/strict'; function throwingFirst() { throw new Error('First'); } function throwingSecond() { throw new Error('Second'); } function notThrowing() {} // The second argument is a string and the input function threw an Error. // The first case will not throw as it does not match for the error message // thrown by the input function! assert.throws(throwingFirst, 'Second'); // In the next example the message has no benefit over the message from the // error and since it is not clear if the user intended to actually match // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. assert.throws(throwingSecond, 'Second'); // TypeError [ERR_AMBIGUOUS_ARGUMENT] // The string is only used (as message) in case the function does not throw: assert.throws(notThrowing, 'Second'); // AssertionError [ERR_ASSERTION]: Missing expected exception: Second // If it was intended to match for the error message do this instead: // It does not throw because the error messages match. assert.throws(throwingSecond, /Second$/); // If the error message does not match, an AssertionError is thrown. assert.throws(throwingFirst, /Second$/); // AssertionError [ERR_ASSERTION]const assert = require('node:assert/strict'); function throwingFirst() { throw new Error('First'); } function throwingSecond() { throw new Error('Second'); } function notThrowing() {} // The second argument is a string and the input function threw an Error. // The first case will not throw as it does not match for the error message // thrown by the input function! assert.throws(throwingFirst, 'Second'); // In the next example the message has no benefit over the message from the // error and since it is not clear if the user intended to actually match // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. assert.throws(throwingSecond, 'Second'); // TypeError [ERR_AMBIGUOUS_ARGUMENT] // The string is only used (as message) in case the function does not throw: assert.throws(notThrowing, 'Second'); // AssertionError [ERR_ASSERTION]: Missing expected exception: Second // If it was intended to match for the error message do this instead: // It does not throw because the error messages match. assert.throws(throwingSecond, /Second$/); // If the error message does not match, an AssertionError is thrown. assert.throws(throwingFirst, /Second$/); // AssertionError [ERR_ASSERTION]
由于符号容易混淆且容易出错,请避免将字符串作为第二个参数。
🌐 Due to the confusing error-prone notation, avoid a string as the second argument.