From 2c9069fd1f7c0fb70f019900e4b841c5ea33975e Mon Sep 17 00:00:00 2001 From: Nitin Kumar Date: Tue, 10 Nov 2020 17:59:04 +0530 Subject: [PATCH] fix: use logger for error with proper exit code (#2076) --- .../utils/__tests__/resolve-command.test.js | 32 +++++++++++++++++++ .../webpack-cli/lib/utils/resolve-command.js | 1 + packages/webpack-cli/lib/utils/run-command.js | 4 ++- 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 packages/webpack-cli/lib/utils/__tests__/resolve-command.test.js diff --git a/packages/webpack-cli/lib/utils/__tests__/resolve-command.test.js b/packages/webpack-cli/lib/utils/__tests__/resolve-command.test.js new file mode 100644 index 00000000000..df10101355e --- /dev/null +++ b/packages/webpack-cli/lib/utils/__tests__/resolve-command.test.js @@ -0,0 +1,32 @@ +jest.setMock('../prompt-installation', jest.fn()); + +const resolveCommand = require('../resolve-command'); +const promptInstallation = require('../prompt-installation'); + +describe('resolve-command util', () => { + const processExitSpy = jest.spyOn(process, 'exit').mockImplementation(() => {}); + const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); + + beforeEach(() => { + processExitSpy.mockClear(); + consoleErrorSpy.mockClear(); + }); + + it('should not throw error', async () => { + promptInstallation.mockImplementation(() => {}); + + await expect(resolveCommand('info')).resolves.not.toThrow(); + expect(processExitSpy.mock.calls.length).toBe(0); + expect(consoleErrorSpy.mock.calls.length).toBe(0); + }); + + it('should throw error and exit with invalid command', async () => { + promptInstallation.mockImplementation(() => { + throw new Error(); + }); + + await resolveCommand('invalid'); + expect(processExitSpy).toBeCalledWith(2); + expect(consoleErrorSpy.mock.calls.length).toBe(1); + }); +}); diff --git a/packages/webpack-cli/lib/utils/resolve-command.js b/packages/webpack-cli/lib/utils/resolve-command.js index 7c39f7067a0..fc4d4e1d08e 100644 --- a/packages/webpack-cli/lib/utils/resolve-command.js +++ b/packages/webpack-cli/lib/utils/resolve-command.js @@ -17,6 +17,7 @@ const run = async (name, ...args) => { }); } catch (err) { logger.error(`Action Interrupted, use ${cyan('webpack-cli help')} to see possible commands.`); + process.exit(2); } } diff --git a/packages/webpack-cli/lib/utils/run-command.js b/packages/webpack-cli/lib/utils/run-command.js index 12e1bd1a4f5..bd5477c1ed1 100644 --- a/packages/webpack-cli/lib/utils/run-command.js +++ b/packages/webpack-cli/lib/utils/run-command.js @@ -1,4 +1,5 @@ const execa = require('execa'); +const logger = require('./logger'); async function runCommand(command, args = []) { try { @@ -7,7 +8,8 @@ async function runCommand(command, args = []) { shell: true, }); } catch (e) { - throw new Error(e); + logger.error(e); + process.exit(2); } }