getUserInput
calls a function when a user enters y
in the CLI prompt:
export const getUserInput = (fn: () => void) => {
const { stdin, stdout } = process;
const rl = readline.createInterface({ input: stdin, output: stdout });
rl.question("Can you confirm? Y/N", (answer: string) => {
if (answer.toLowerCase() === "y") {
fn();
}
rl.close();
});
};
I need to create a test for getUserInput
mocking Node's readline
.
Currently I have tried the following but with no success, getting:
TypeError: rl.close is not a function
Is my mock implementation correct, and if not how can I fix it?
jest.mock("readline");
describe.only("program", () => {
it.only("should execute a cb when user prompt in cli y", () => {
const mock = jest.fn();
getUserInput(mock);
expect(mock).toHaveBeenCalled();
});
});
__mocks__/readline.ts
(directory adjacent to node_module)
module.exports ={
createInterface :jest.fn().mockReturnValue({
question:jest.fn().mockImplementationOnce((_questionTest, cb)=> cb('y'))
})
}
I was able to solve this issue by adding a mock the close
function.
module.exports = {
createInterface: jest.fn().mockReturnValue({
question: jest.fn().mockImplementationOnce((_questionTest, cb) => cb("y")),
close: jest.fn().mockImplementationOnce(() => undefined)
})
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With