This is my test.
I am running a child process which runs a bash script that ask for the user to input something.
I want to write back to the stdin but its failing.
prompt-user.test.ts
import { spawn } from "child_process";
describe("node interactive cli test", () => {
it("should prompt user and we write response to get feedback output", async () => {
const arrData: string[] = [];
const child = spawn(
'bash', ['prompt-user.sh']
); // works
child.stdout?.on("readable", () => {
console.log("on readable - write back to stream");
// output: on readable - write back to stream
child.stdin?.write(`Yn`); // output:
// write EPIPE
// > 11 | child.stdin?.write(`Yn`);
});
child.stdout?.on("message", (message: any, x: any, y: any) => {
console.log('on message', message);
});
child.stdout?.on("data", (data: any, x: any, y: any) => {
const dataAsString = data.toString();
console.log('dataAsString =', dataAsString);
arrData.push(dataAsString);
});
child.stdout?.on("error", (err) => {
console.log("error=", err);
});
await new Promise((resolve, reject) => {
child.on("end", () => {
resolve(true);
});
});
expect(arrData.indexOf("Yes") !== -1).toBe(true);
});
});
This is the bash file, which works in its own right
prompt-user.sh
#/bin/bash
printf 'Is this a good question (y/n)? '
read answer
if [ "$answer" != "${answer#[Yy]}" ] ;then
echo Yes
else
echo No
fi
I get error:
write EPIPE on child.stdin?.write(
Yn
);