-
Notifications
You must be signed in to change notification settings - Fork 934
/
Copy pathinput.test.ts
97 lines (89 loc) · 2.51 KB
/
input.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/// <reference path="./inquirer/inquirer.d.ts" />
import {test, expect, vi} from 'vitest';
// @ts-expect-error -- no typings
import config from '@commitlint/config-angular';
import chalk from 'chalk';
import {Answers, DistinctQuestion, PromptModule} from 'inquirer';
import {input} from './input.js';
vi.mock('@commitlint/load', () => ({
default: () => config,
}));
test('should work with all fields filled', async () => {
const prompt = stub({
'input-custom': {
type: 'fix',
scope: 'test',
subject: 'subject',
body: 'body',
footer: 'footer',
},
});
const message = await input(prompt);
expect(message).toEqual('fix(test): subject\n' + 'body\n' + 'footer');
});
test('should work without scope', async () => {
const prompt = stub({
'input-custom': {
type: 'fix',
scope: '',
subject: 'subject',
body: 'body',
footer: 'footer',
},
});
const message = await input(prompt);
expect(message).toEqual('fix: subject\n' + 'body\n' + 'footer');
});
test('should fail without type', async () => {
const spy = vi.spyOn(console, 'error');
const prompt = stub({
'input-custom': {
type: '',
scope: '',
subject: '',
body: '',
footer: '',
},
});
const message = await input(prompt);
expect(message).toEqual('');
expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenLastCalledWith(
new Error(`⚠ ${chalk.bold('type')} may not be empty.`)
);
spy.mockRestore();
});
function stub(config: Record<string, Record<string, unknown>>): PromptModule {
const prompt = async (
questions: DistinctQuestion | DistinctQuestion[]
): Promise<any> => {
const result: Answers = {};
const resolvedConfig = Array.isArray(questions) ? questions : [questions];
for (const promptConfig of resolvedConfig) {
const configType = promptConfig.type || 'input';
const questions = config[configType];
if (!questions) {
throw new Error(`Unexpected config type: ${configType}`);
}
const answer = questions[promptConfig.name!];
if (answer == null) {
throw new Error(`Unexpected config name: ${promptConfig.name}`);
}
const validate = promptConfig.validate;
if (validate) {
const validationResult = await validate(answer, result);
if (validationResult !== true) {
throw new Error(validationResult || undefined);
}
}
result[promptConfig.name!] = answer;
}
return result;
};
prompt.registerPrompt = () => {
return prompt;
};
prompt.restoreDefaultPrompts = () => true;
prompt.prompts = {};
return prompt as any as PromptModule;
}