diff --git a/lib/test.js b/lib/test.js index 3b3b255..27fb76c 100644 --- a/lib/test.js +++ b/lib/test.js @@ -308,6 +308,12 @@ function wrapAssertFn(assertFn) { err = assertFn(res); } catch (e) { err = e; + + // Handle errors that fail `instanceof Error`, like `throw 1;` or dealing with multiple realms/contexts: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_realms + if (!(err instanceof Error)) { + err = new Error(err); + } } if (err instanceof Error && err.stack) { badStack = err.stack.replace(err.message, '').split('\n').slice(1); diff --git a/test/supertest.js b/test/supertest.js index 9eebf31..c36b665 100644 --- a/test/supertest.js +++ b/test/supertest.js @@ -871,6 +871,20 @@ describe('request(app)', function () { .expect('Content-Type', /text/) .end(done); }); + + it('fails for non-Error values that are thrown', function (done) { + get + .expect(function (res) { + // eslint-disable-next-line no-throw-literal + throw 'error123'; + }) + .end(function (err) { + should.exist(err); + err.message.should.equal('error123'); + shouldIncludeStackWithThisFile(err); + done(); + }); + }); }); describe('handling multiple assertions per field', function () {