Skip to content

Instantly share code, notes, and snippets.

@yyx990803
Last active Jul 15, 2021
Embed
What would you like to do?
// place this file in __mocks__
let pendingAssertions
exports.prompt = prompts => {
if (!pendingAssertions) {
throw new Error(`inquirer was mocked and used without pending assertions: ${prompts}`)
}
const answers = {}
let skipped = 0
prompts.forEach((prompt, i) => {
if (prompt.when && !prompt.when(answers)) {
skipped++
return
}
const setValue = val => {
if (prompt.validate) {
const res = prompt.validate(val)
if (res !== true) {
throw new Error(`validation failed for prompt: ${prompt}`)
}
}
answers[prompt.name] = prompt.filter
? prompt.filter(val)
: val
}
const a = pendingAssertions[i - skipped]
if (a.message) {
const message = typeof prompt.message === 'function'
? prompt.message(answers)
: prompt.message
expect(message).toContain(a.message)
}
if (a.choices) {
expect(prompt.choices.length).toBe(a.choices.length)
a.choices.forEach((c, i) => {
const expected = a.choices[i]
if (expected) {
expect(prompt.choices[i].name).toContain(expected)
}
})
}
if (a.input != null) {
expect(prompt.type).toBe('input')
setValue(a.input)
}
if (a.choose != null) {
expect(prompt.type).toBe('list')
setValue(prompt.choices[a.choose].value)
}
if (a.check != null) {
expect(prompt.type).toBe('checkbox')
setValue(a.check.map(i => prompt.choices[i].value))
}
if (a.confirm != null) {
expect(prompt.type).toBe('confirm')
setValue(a.confirm)
}
if (a.useDefault) {
expect('default' in prompt).toBe(true)
setValue(
typeof prompt.default === 'function'
? prompt.default(answers)
: prompt.default
)
}
})
expect(prompts.length).toBe(pendingAssertions.length + skipped)
pendingAssertions = null
return Promise.resolve(answers)
}
exports.expectPrompts = assertions => {
pendingAssertions = assertions
}
jest.mock('inquirer')
const { prompt, expectPrompts } = require('inquirer')
it('should pass', async () => {
// specify expected prompts and corresponding actions
// before making the prompt
expectPrompts([
{
message: 'Hello',
choices: ['Foo', 'Bar'],
check: [0, 1]
},
{
message: 'World',
choices: ['Baz', 'Qux'],
choose: 0
},
{
message: 'Really ok?',
confirm: true
}
])
// then just use inquirer as normal.
// if a imported mdoule uses inquirer, it's also using the mocked version.
const answers = await prompt([
{
name: 'hello',
message: 'Hello with some extra text',
type: 'checkbox',
choices: [
{ name: 'Foo', value: 'foo' },
{ name: 'Bar', value: 'bar' }
]
},
{
name: 'world',
message: 'World',
type: 'list',
choices: [
{ name: 'Baz', value: 'baz' },
{ name: 'Qux', value: 'qux' }
]
},
{
name: 'ok',
message: 'Really ok?',
type: 'confirm'
}
])
expect(answers).toEqual({
hello: ['foo', 'bar'],
world: 'baz',
ok: true
})
})
@good-idea

This comment has been minimized.

Copy link

@good-idea good-idea commented Jul 3, 2020

This is fantastic, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment