Skip to content

Commit 67d696c

Browse files
committed
test: add CLI error handling tests
1 parent 95698f4 commit 67d696c

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import * as rockTools from '@rock-js/tools';
2+
3+
import { expect, Mock, test, vi } from 'vitest';
4+
5+
import { actionRunner } from '../cli.js';
6+
7+
vi.mock('@rock-js/tools', async (importOriginal) => {
8+
const actual = await importOriginal<typeof rockTools>();
9+
return {
10+
...actual,
11+
logger: {
12+
...actual.logger,
13+
error: vi.fn(),
14+
warn: vi.fn(),
15+
info: vi.fn(),
16+
success: vi.fn(),
17+
},
18+
};
19+
});
20+
21+
// @ts-expect-error - override typings
22+
const processExitMock = vi.spyOn(process, 'exit').mockImplementation(() => {
23+
// no-op
24+
});
25+
26+
const mockLoggerError = rockTools.logger.error as Mock;
27+
28+
const FAILING_ACTION_ERROR_MESSAGE = 'Test error';
29+
30+
const createWrappedFailingAction = (ErrorCls: new (message: string) => Error) =>
31+
actionRunner(async (_a: number, _b: number) => {
32+
throw new ErrorCls(FAILING_ACTION_ERROR_MESSAGE);
33+
});
34+
35+
test('actionRunner should call the wrapped function', async () => {
36+
const mockAction = vi.fn(async () => Promise.resolve());
37+
const wrappedAction = actionRunner(mockAction);
38+
39+
await wrappedAction();
40+
41+
expect(mockAction).toHaveBeenCalledOnce();
42+
});
43+
44+
test('actionRunner should gracefully handle Errors', async () => {
45+
const wrappedActionExpectation = expect(
46+
createWrappedFailingAction(Error)(1, 2)
47+
);
48+
49+
await wrappedActionExpectation.resolves.not.toThrowError();
50+
expect(processExitMock).toHaveBeenCalledExactlyOnceWith(1);
51+
expect(mockLoggerError).toHaveBeenCalled();
52+
});
53+
54+
test('actionRunner should gracefully handle RockErrors', async () => {
55+
const wrappedActionExpectation = expect(
56+
createWrappedFailingAction(rockTools.RockError)(1, 2)
57+
);
58+
59+
await wrappedActionExpectation.resolves.not.toThrowError();
60+
expect(processExitMock).toHaveBeenCalledExactlyOnceWith(1);
61+
expect(mockLoggerError).toHaveBeenCalled();
62+
});

0 commit comments

Comments
 (0)