execa icon indicating copy to clipboard operation
execa copied to clipboard

Mocking stdin for multiple prompts

Open open-source-explorer opened this issue 4 years ago • 6 comments

Say, I'm writing integration tests for a given feature in a CLI tooling which has got multiple user prompts.

rootcmd arg results in couple of prompts-

Do you need X? (Y/N)? Y

Another prompt here (Y/N)? N

As a result a file is created.

I need to write integration tests in such a way that choices to above prompts are given via the test environment. I can write to stdin for the very first prompt in the following fashion:-

const {stdout} = execa(__dirname, args, {input: 'y'});

But as said it only works for the very first prompt. How should I be able to do the same for future prompts as well and thereby checking existence for the file?

open-source-explorer avatar Apr 07 '20 16:04 open-source-explorer

Hi @open-source-explorer,

I have not tried it locally but would inserting newlines work?

const {stdout} = execa(__dirname, args, {input: 'Y\nN\n'});

ehmicky avatar Apr 07 '20 16:04 ehmicky

@ehmicky that doesn't seem to work. I was expecting to find something like this one:-

const {stdin, stdout} = execa(__dirname, args, {input: 'y'}); // writes to stdin for the first time.
stdin.write('y'); // writes to stdin for the second time.
stdin.end();

open-source-explorer avatar Apr 08 '20 05:04 open-source-explorer

Also, in the above context the return value from execa lacks stdin. For instance,

const subProcess = execa(__dirname, args, {input: 'y', stdio: 'pipe'});
console.log(subProcess.hasOwnProperty('stdin')); // false

Am I doing something wrong?

open-source-explorer avatar Apr 08 '20 05:04 open-source-explorer

Hi. I'm here with the same question :) As I use execa for integration testing of a CLI tool and I need this to test that prompts are working.

RIP21 avatar Aug 21 '20 21:08 RIP21

@RIP21 this might be useful for you: https://github.com/jamesgeorge007/cli-prompts-test

open-source-explorer avatar Aug 22 '20 17:08 open-source-explorer

@open-source-explorer lol how come it was released 7 hrs ago? :D I already adopted some other handy function for that. But I'll rewrite using this one maybe :)

RIP21 avatar Aug 22 '20 18:08 RIP21

This is a timing issue.

Namely, once you write the initial y, the first prompt processes it. It needs some time before displaying the second prompt and listening for more stdin data. Only then, one must write more stdin data. I.e. you need to either:

  • Coordinate between both the logic doing the prompts and the logic writing to stdin so they wait for each other
  • Introduce sleep times

Closing as this is not a bug related to Execa.

ehmicky avatar Dec 18 '23 03:12 ehmicky