|
| 1 | +let pendingAssertions |
| 2 | + |
| 3 | +exports.prompt = prompts => { |
| 4 | + if (!pendingAssertions) { |
| 5 | + throw new Error(`inquirer was mocked and used without pending assertions: ${prompts}`) |
| 6 | + } |
| 7 | + |
| 8 | + const answers = {} |
| 9 | + let skipped = 0 |
| 10 | + prompts.forEach((prompt, i) => { |
| 11 | + if (prompt.when && !prompt.when(answers)) { |
| 12 | + skipped++ |
| 13 | + return |
| 14 | + } |
| 15 | + |
| 16 | + const setValue = val => { |
| 17 | + if (prompt.validate) { |
| 18 | + const res = prompt.validate(val) |
| 19 | + if (res !== true) { |
| 20 | + throw new Error(`validation failed for prompt: ${prompt}`) |
| 21 | + } |
| 22 | + } |
| 23 | + answers[prompt.name] = prompt.filter |
| 24 | + ? prompt.filter(val) |
| 25 | + : val |
| 26 | + } |
| 27 | + |
| 28 | + const a = pendingAssertions[i - skipped] |
| 29 | + if (!a) { |
| 30 | + console.error(`no matching assertion for prompt:`, prompt) |
| 31 | + console.log(prompts) |
| 32 | + console.log(pendingAssertions) |
| 33 | + } |
| 34 | + |
| 35 | + if (a.message) { |
| 36 | + const message = typeof prompt.message === 'function' |
| 37 | + ? prompt.message(answers) |
| 38 | + : prompt.message |
| 39 | + expect(message).toMatch(a.message) |
| 40 | + } |
| 41 | + |
| 42 | + const choices = typeof prompt.choices === 'function' |
| 43 | + ? prompt.choices(answers) |
| 44 | + : prompt.choices |
| 45 | + if (a.choices) { |
| 46 | + expect(choices.length).toBe(a.choices.length) |
| 47 | + a.choices.forEach((c, i) => { |
| 48 | + const expected = a.choices[i] |
| 49 | + if (expected) { |
| 50 | + expect(choices[i].name).toMatch(expected) |
| 51 | + } |
| 52 | + }) |
| 53 | + } |
| 54 | + |
| 55 | + if (a.input != null) { |
| 56 | + expect(prompt.type).toBe('input') |
| 57 | + setValue(a.input) |
| 58 | + } |
| 59 | + |
| 60 | + if (a.choose != null) { |
| 61 | + expect(prompt.type === 'list' || prompt.type === 'rawList').toBe(true) |
| 62 | + setValue(choices[a.choose].value) |
| 63 | + } |
| 64 | + |
| 65 | + if (a.check != null) { |
| 66 | + expect(prompt.type).toBe('checkbox') |
| 67 | + setValue(a.check.map(i => choices[i].value)) |
| 68 | + } |
| 69 | + |
| 70 | + if (a.confirm != null) { |
| 71 | + expect(prompt.type).toBe('confirm') |
| 72 | + setValue(a.confirm) |
| 73 | + } |
| 74 | + |
| 75 | + if (a.useDefault) { |
| 76 | + expect('default' in prompt).toBe(true) |
| 77 | + setValue( |
| 78 | + typeof prompt.default === 'function' |
| 79 | + ? prompt.default(answers) |
| 80 | + : prompt.default |
| 81 | + ) |
| 82 | + } |
| 83 | + }) |
| 84 | + |
| 85 | + expect(prompts.length).toBe(pendingAssertions.length + skipped) |
| 86 | + pendingAssertions = null |
| 87 | + |
| 88 | + return Promise.resolve(answers) |
| 89 | +} |
| 90 | + |
| 91 | +exports.expectPrompts = assertions => { |
| 92 | + pendingAssertions = assertions |
| 93 | +} |
0 commit comments