From bd478e77532c217ffa8673ca201e815946c5f022 Mon Sep 17 00:00:00 2001 From: Jonatan Nilsson Date: Mon, 28 Aug 2023 06:25:22 +0000 Subject: [PATCH] assert: Add new feature throwsAndCatch, returns the original thrown error --- README.md | 9 +++++++++ lib/assert.mjs | 9 +++++++++ package.json | 2 +- test/assert.test.mjs | 22 ++++++++++++++++++++++ 4 files changed, 41 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 173571f..93b55d1 100644 --- a/README.md +++ b/README.md @@ -458,6 +458,15 @@ let err = await assert.isRejected(() => { throw new Error('hello') }) // ok assert.strictEqual(err.message, 'hello') ``` +### assert.throwsAndCatch(fn[, message]) + +Tests to make sure the function throws an exception. The important feature is this returns the original error that was thrown. + +```javascript +let err = assert.throwsAndCatch(() => { throw new Error('hello world') }) // ok +assert.strictEqual(err.message, 'hello world') +``` + # Sinon-like spy() stub() Using sinon-inspired mechanics for spying on calls as well as being able diff --git a/lib/assert.mjs b/lib/assert.mjs index 0d7cc06..e4fa038 100644 --- a/lib/assert.mjs +++ b/lib/assert.mjs @@ -48,6 +48,15 @@ assert.notMatch = (value, test, message) => { fail(m); } +assert.throwsAndCatch = (fn, message) => { + let err = null + assert.throws(fn, function(error) { + err = error + return true + }, message) + return err +} + assert.isFulfilled = (promise, message) => { return Promise.resolve(true) .then(() => promise) diff --git a/package.json b/package.json index 2b0ef0a..d729388 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "eltro", - "version": "1.3.3", + "version": "1.3.4", "description": "Eltro is a tiny no-dependancy test framework for node", "main": "index.mjs", "scripts": { diff --git a/test/assert.test.mjs b/test/assert.test.mjs index 6331300..69d16f2 100644 --- a/test/assert.test.mjs +++ b/test/assert.test.mjs @@ -29,6 +29,28 @@ t.describe('#notOk()', function() { }) }) +t.describe('#throwAndCatch()', function() { + t.test('should work and return the original error', function() { + const assertError = new Error('Speed') + + let err = assert.throwsAndCatch(() => { throw assertError }) + assert.strictEqual(err, assertError) + }) + + t.test('should otherwise throw if no error', function() { + const assertMessage = 'Hello world' + let error = null + + try { + assert.throwsAndCatch(() => { }, assertMessage) + } catch (err) { + error = err + } + assert.ok(error) + assert.match(error.message, new RegExp(assertMessage)) + }) +}) + t.describe('#isFulfilled()', function() { t.test('should exist', function() { assertExtended.ok(assertExtended.isFulfilled)