From 489afd8799af1d2d4850cf35256aaa7676cfd225 Mon Sep 17 00:00:00 2001 From: killa Date: Sat, 5 Aug 2023 15:18:19 +0800 Subject: [PATCH] fix: convert unhandled rejection to uncaught exception (#235) Mocha do not catch unhandled rejection by default. Case will faield until timeout. set `--unhandled-rejections` to strict, let case fail fast. --- lib/cmd/test.js | 6 +++++- test/fixtures/test-unhandled-rejection/package.json | 6 ++++++ test/fixtures/test-unhandled-rejection/test/a.test.js | 7 +++++++ test/lib/cmd/test.test.js | 7 +++++++ 4 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/test-unhandled-rejection/package.json create mode 100644 test/fixtures/test-unhandled-rejection/test/a.test.js diff --git a/lib/cmd/test.js b/lib/cmd/test.js index 7c2d3ea1..644c2390 100644 --- a/lib/cmd/test.js +++ b/lib/cmd/test.js @@ -90,7 +90,11 @@ class TestCommand extends Command { env: Object.assign({ NODE_ENV: 'test', }, context.env), - execArgv: context.execArgv, + execArgv: [ + ...context.execArgv, + // https://github.com/mochajs/mocha/issues/2640#issuecomment-1663388547 + '--unhandled-rejections=strict', + ], }; await this.helper.forkNode(mochaFile, testArgs, opt); } diff --git a/test/fixtures/test-unhandled-rejection/package.json b/test/fixtures/test-unhandled-rejection/package.json new file mode 100644 index 00000000..1633ac83 --- /dev/null +++ b/test/fixtures/test-unhandled-rejection/package.json @@ -0,0 +1,6 @@ +{ + "name": "test-unhandled-rejection", + "files": [ + "lib" + ] +} diff --git a/test/fixtures/test-unhandled-rejection/test/a.test.js b/test/fixtures/test-unhandled-rejection/test/a.test.js new file mode 100644 index 00000000..e10d4e69 --- /dev/null +++ b/test/fixtures/test-unhandled-rejection/test/a.test.js @@ -0,0 +1,7 @@ +'use strict'; + +describe('a.test.js', () => { + it('should success', () => { + Promise.reject(new Error('mock error')); + }); +}); diff --git a/test/lib/cmd/test.test.js b/test/lib/cmd/test.test.js index 69648ce1..8aad4d78 100644 --- a/test/lib/cmd/test.test.js +++ b/test/lib/cmd/test.test.js @@ -291,6 +291,13 @@ describe('test/lib/cmd/test.test.js', () => { .expect('stdout', /env\.AUTO_AGENT: true/) .expect('stdout', /env\.ENABLE_MOCHA_PARALLEL: true/) .expect('code', 0) + }); + + it('should failed with unhandled rejection', () => { + return coffee.fork(eggBin, [ 'test' ], { cwd: path.join(__dirname, '../../fixtures/test-unhandled-rejection') }) + .debug() + .expect('stdout', / Uncaught Error: mock error/) + .expect('code', 1) .end(); }); });