How to use the throws function from assert
Find comprehensive JavaScript assert.throws code examples handpicked from public code repositorys.
assert.throws is a Node.js assertion method that checks if a given function throws an error or not.
407 408 409 410 411 412 413 414 415 416
it(`when ${name}`, () => { if (setup) { setup(); } const regex = new RegExp(errorMsg); assert.throws(() => { videoTrack.removeProcessor(getParam()); }, regex); }); }); }); });
GitHub: algorand/js-algorand-sdk
4028 4029 4030 4031 4032 4033 4034 4035 4036 4037
break; default: throw new Error(`Unknown error type: "${errorType}"`); } assert.throws( () => this.composer.buildGroup(), (err) => err.message === expectedMessage ); }
How does assert.throws work?
assert.throws is a method provided by the Node.js assert module that tests if a given function throws an error or not when it's called. It takes a function as its first argument and an optional error object or constructor as its second argument. If the function throws an error that matches the error object or constructor provided, the assertion passes. If not, the assertion fails.
GitHub: dependents/node-precinct
189 190 191 192 193 194 195 196 197
assert.notEqual(precinct.paperwork(path.join(__dirname, '/fixtures/typescript.ts')).length, 0); assert.notEqual(precinct.paperwork(path.join(__dirname, '/fixtures/styles.css')).length, 0); }); it('throws if the file cannot be found', () => { assert.throws(() => { precinct.paperwork('foo'); }); });
546 547 548 549 550 551 552 553 554 555 556 557
throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); };
Ai Example
1 2 3 4 5 6 7
const assert = require("assert"); function throwError() { throw new Error("This is an error"); } assert.throws(throwError, /error/);
In this example, we define a function throwError that always throws an error. We then use assert.throws to check if calling this function will throw an error that matches the regular expression /error/. If the function does not throw an error or if the error message does not match the regular expression, the assert function will throw an AssertionError.
23 24 25 26 27 28 29 30 31 32
nucleoid.run("var j = 1 ;"); equal(nucleoid.run("j + 2"), 3); }); it("rejects variable declaration without definition", () => { throws( () => { nucleoid.run("var a"); }, (error) => validate(error, SyntaxError, "Missing definition")
+ 113 other calls in file
143 144 145 146 147 148 149 150 151
}) it('should throw an exception for an undefined date format', function() { var test_date = new Date(Date.UTC(2014, 08, 10, 16, 05, 38));//'Wed Sep 10 2014 16:05:38 GMT+0100 (BST)'); assert.throws(function() { DateVal.date_with_format_array(test_date, undefined); }, Error); })
+ 8 other calls in file
312 313 314 315 316 317 318 319 320
const logErrorSpy = sinon.spy(Logger.prototype, 'error'); const declarationParser = new DeclarationParser(declaration, undefined, { id: '123-abc' }); sinon.stub(parserUtil, 'updateIds').throws(new Error('test error')); assert.throws(() => declarationParser.parse(), /test error/); assert.strictEqual(logErrorSpy.thisValues[0].metadata, 'declarationParser.js | 123-abc'); assert.strictEqual(logErrorSpy.args[0][0], 'Error parsing declaration test error'); });
GitHub: nodejs/node-addon-api
15 16 17 18 19 20 21 22 23 24
assert.throws(() => binding.error.throwApiError('test'), function (err) { return err instanceof Error && err.message.includes('Invalid'); }); assert.throws(() => binding.error.lastExceptionErrorCode(), function (err) { return err instanceof TypeError && err.message === 'A boolean was expected'; }); assert.throws(() => binding.error.throwJSError('test'), function (err) {
+ 13 other calls in file
GitHub: wingbotai/wingbot
67 68 69 70 71 72 73 74 75 76
// @ts-ignore assert(!isStringNumber({ x: '5' })); }); it('stringToNumber', () => { assert.throws(() => stringToNumber('1a')); assert.throws(() => stringToNumber('NaN')); assert(stringToNumber('123') === 123); assert(stringToNumber('123 5') === 1235); assert(stringToNumber('100,500.23') === 100500.23);
+ 3 other calls in file
GitHub: bonavadeur/konnichiwa
522 523 524 525 526 527 528 529 530
extra bytes are added to the message. The test uses a message of 118 bytes.Together with the 11 extra bytes the encryption block needs to be at least 129 bytes long. This requires a key of 1025-bits. */ var key = PKI.publicKeyFromPem(tests[0].publicKeyPem); var message = UTIL.createBuffer().fillWithByte(0, 118); ASSERT.throws(function() { key.encrypt(message.getBytes()); }); });
+ 2 other calls in file
6 7 8 9 10 11 12 13 14 15
}) context('exception when receives', () => { it('an empty object', function () { const res = () => json2csv({}) assert.throws(res, Error) }) it('an empty string', () => { const res = () => json2csv('')
+ 7 other calls in file
417 418 419 420 421 422 423 424 425 426
}) }) describe('with verify option', function () { it('should assert value if function', function () { assert.throws(createApp.bind(null, { verify: 'lol' }), /TypeError: option verify must be function/) }) it('should error from verify', function (done) {
38 39 40 41 42 43 44 45 46 47
}) describe('"etag"', function(){ it('should throw on bad value', function(){ var app = express(); assert.throws(app.set.bind(app, 'etag', 42), /unknown value/); }) it('should set "etag fn"', function(){ var app = express()
98 99 100 101 102 103 104 105 106 107
}); }); describe('when "query parser" an unknown value', function () { it('should throw', function () { assert.throws(createApp.bind(null, 'bogus'), /unknown value.*query parser/) }); }); })
48 49 50 51 52 53 54 55 56 57
const { value } = expr.next(); assert.strictEqual(value.sign, '~'); assert.strictEqual(value.text, '~{x = something}'); assert.strictEqual(value.test[0](), true); assert.throws(() => expr.next(), new Error('unexpected "x > 0"')); }); it('must register new clause and repeat previous', () => { q.register({
+ 3 other calls in file
GitHub: mansimodiTrootech/repoC
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
0.0, 0, [], {} ].forEach(function(val) { assert.throws(function() { url.parse(val); }, TypeError); }); //
930 931 932 933 934 935 936 937 938 939 940
message: 'false == true' } ); assert.throws( () => assert.throws(() => {}, 'Error message', 'message'), { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError', message: 'The "error" argument must be of type function or ' +
+ 71 other calls in file
87 88 89 90 91 92 93 94 95 96 97 98
function checkErr(err) { return err.stack.startsWith('test-boom-error:1'); } assert.throws(() => vm.runInContext(script, context, filename), checkErr); assert.throws(() => vm.runInNewContext(script, context, filename), checkErr); assert.throws(() => vm.runInThisContext(script, filename), checkErr); }
+ 35 other calls in file
33 34 35 36 37 38 39 40 41 42
assert.notDeepStrictEqual(oldServerSettings, newServerSettings); server.updateSettings(newServerSettings); const updatedServerSettings = getServerSettings(server); assert.deepStrictEqual(updatedServerSettings, { ...oldServerSettings, ...newServerSettings }); assert.throws(() => server.updateSettings(''), { message: 'The "settings" argument must be of type object. ' + 'Received type string (\'\')', code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError'
+ 3 other calls in file
11 12 13 14 15 16 17 18 19 20 21
// is a TTY. if (process.stdout.isTTY) process.env.NODE_DISABLE_COLORS = '1'; // Template tag function turning an error message into a RegExp // for assert.throws() function re(literals, ...values) { let result = 'Expected values to be loosely deep-equal:\n\n'; for (const [i, value] of values.entries()) { const str = util.inspect(value, {
+ 33 other calls in file
assert.equal is the most popular function in assert (3580 examples)