首页 > 解决方案 > 如何模拟节点readline?

问题描述

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();
  });
};

我需要为getUserInput模拟 Node 的readline.

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

TypeError: rl.close is not a function

我的模拟实现是否正确,如果不正确,我该如何解决?

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(与 node_module 相邻的目录)

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

标签: javascriptnode.jstypescriptjestjs

解决方案


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

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

推荐阅读