UNPKG

2.14 kBJavaScriptView Raw
1'use strict';
2var events = require('events');
3var _ = require('lodash');
4var inquirer = require('inquirer');
5var sinon = require('sinon');
6var { PassThrough } = require('stream');
7
8function DummyPrompt(mockedAnswers, callback, question, _rl, answers) {
9 this.answers = { ...answers, ...mockedAnswers };
10 this.question = question;
11 this.callback = callback || (answers => answers);
12}
13
14DummyPrompt.prototype.run = function() {
15 var answer = this.answers[this.question.name];
16 var isSet;
17
18 switch (this.question.type) {
19 case 'list':
20 // List prompt accepts any answer value including null
21 isSet = answer !== undefined;
22 break;
23 case 'confirm':
24 // Ensure that we don't replace `false` with default `true`
25 isSet = answer || answer === false;
26 break;
27 default:
28 // Other prompts treat all falsy values to default
29 isSet = Boolean(answer);
30 }
31
32 if (!isSet) {
33 answer = this.question.default;
34
35 if (answer === undefined && this.question.type === 'confirm') {
36 answer = true;
37 }
38 }
39
40 return Promise.resolve(this.callback(answer));
41};
42
43function TestAdapter(answers) {
44 answers = answers || {};
45 this.promptModule = inquirer.createPromptModule({
46 input: new PassThrough(),
47 output: new PassThrough(),
48 skipTTYChecks: true
49 });
50
51 Object.keys(this.promptModule.prompts).forEach(function(promptName) {
52 this.promptModule.registerPrompt(
53 promptName,
54 DummyPrompt.bind(DummyPrompt, answers, undefined)
55 );
56 }, this);
57
58 this.diff = sinon.spy();
59 this.log = sinon.spy();
60 _.extend(this.log, events.EventEmitter.prototype);
61
62 // Make sure all log methods are defined
63 [
64 'write',
65 'writeln',
66 'ok',
67 'error',
68 'skip',
69 'force',
70 'create',
71 'invoke',
72 'conflict',
73 'identical',
74 'info',
75 'table'
76 ].forEach(function(methodName) {
77 this.log[methodName] = sinon.stub().returns(this.log);
78 }, this);
79}
80
81TestAdapter.prototype.prompt = function(questions, prefilledAnswers) {
82 return this.promptModule(questions, prefilledAnswers);
83};
84
85module.exports = {
86 DummyPrompt: DummyPrompt,
87 TestAdapter: TestAdapter
88};