diff --git a/packages/vitest/src/node/cli-api.ts b/packages/vitest/src/node/cli-api.ts index 1cb2bc2dc5d1..542a6e61982c 100644 --- a/packages/vitest/src/node/cli-api.ts +++ b/packages/vitest/src/node/cli-api.ts @@ -79,6 +79,8 @@ export async function startVitest( if (process.stdin.isTTY && ctx.config.watch) registerConsoleShortcuts(ctx) + else + process.on('SIGINT', () => ctx.cancelCurrentRun('keyboard-input')) ctx.onServerRestart((reason) => { ctx.report('onServerRestart', reason) diff --git a/packages/vitest/src/node/stdin.ts b/packages/vitest/src/node/stdin.ts index 20bbd7ab3eee..4d697ae96f57 100644 --- a/packages/vitest/src/node/stdin.ts +++ b/packages/vitest/src/node/stdin.ts @@ -28,9 +28,15 @@ export function registerConsoleShortcuts(ctx: Vitest) { let latestFilename = '' async function _keypressHandler(str: string, key: any) { - // ctrl-c or esc - if (str === '\x03' || str === '\x1B' || (key && key.ctrl && key.name === 'c')) + // Cancel run and exit when ctrl-c or esc is pressed. + // If cancelling takes long and key is pressed multiple times, exit forcefully. + if (str === '\x03' || str === '\x1B' || (key && key.ctrl && key.name === 'c')) { + if (!ctx.isCancelling) { + await ctx.cancelCurrentRun('keyboard-input') + await ctx.runningPromise + } return ctx.exit(true) + } // window not support suspend if (!isWindows && key && key.ctrl && key.name === 'z') {