WXL
4 天以前 3bd962a6d7f61239c020e2dbbeb7341e5b842dd1
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
98
99
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, index) => {
    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[index - skipped]
    if (!a) {
      console.error(`no matching assertion for prompt:`, prompt)
      console.log(prompts)
      console.log(pendingAssertions)
    }
 
    if (a.message) {
      const message =
        typeof prompt.message === 'function'
          ? prompt.message(answers)
          : prompt.message
      expect(message).toMatch(a.message)
    }
 
    const choices =
      typeof prompt.choices === 'function'
        ? prompt.choices(answers)
        : prompt.choices
    if (a.choices) {
      expect(choices.length).toBe(a.choices.length)
      a.choices.forEach((c, i) => {
        const expected = a.choices[i]
        if (expected) {
          expect(choices[i].name).toMatch(expected)
        }
      })
    }
 
    if (a.input != null) {
      expect(prompt.type).toBe('input')
      setValue(a.input)
    }
 
    if (a.choose != null) {
      expect(prompt.type === 'list' || prompt.type === 'rawList').toBe(true)
      setValue(choices[a.choose].value)
    }
 
    if (a.check != null) {
      expect(prompt.type).toBe('checkbox')
      setValue(a.check.map(i => 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.createPromptModule = () => {
  return exports.prompt
}
 
exports.expectPrompts = assertions => {
  pendingAssertions = assertions
}