如何模拟节点readline?

Gib*_*boK 5 javascript node.js typescript jestjs

getUserInputy当用户在 CLI 提示符中输入时调用函数:

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();
  });
};
Run Code Online (Sandbox Code Playgroud)

我需要创建一个测试来getUserInput模拟 Node 的readline.

目前我已尝试以下但没有成功,得到:

TypeError: rl.close is not a function
Run Code Online (Sandbox Code Playgroud)

我的模拟实现正确吗?如果不正确我该如何修复它?

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();
     });
 });
Run Code Online (Sandbox Code Playgroud)

__mocks__/readline.ts(与node_module相邻的目录)

module.exports ={
  createInterface :jest.fn().mockReturnValue({
    question:jest.fn().mockImplementationOnce((_questionTest, cb)=> cb('y'))
  })
}
Run Code Online (Sandbox Code Playgroud)

Gib*_*boK 3

我能够通过添加模拟函数来解决这个问题close

module.exports = {
  createInterface: jest.fn().mockReturnValue({
    question: jest.fn().mockImplementationOnce((_questionTest, cb) => cb("y")),
    close: jest.fn().mockImplementationOnce(() => undefined)
  })
};
Run Code Online (Sandbox Code Playgroud)