javascript - 如何模拟 Node readline?

标签 javascript node.js typescript jestjs

getUserInput 当用户在 CLI 提示中输入 y 时调用函数:

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

我需要为模拟 Node 的 readlinegetUserInput 创建一个测试。

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

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'))
  })
}

最佳答案

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

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

关于javascript - 如何模拟 Node readline?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54060367/

相关文章:

javascript - 四舍五入的百分比加法闭合

javascript - 为什么这种计算数组重复项并将其存储到对象中的方法有效?

angularjs - 我可以在函数中创建一个 TypeScript 类并引用它的参数吗?

node.js - NodeJs sharp Image library - Resize using Stream Api 抛出错误 'stream.push() after EOF'

javascript - 如何在 Angular 2 模板中使用外部 Javascript 函数?

javascript - 如何使用 TypeScript 声明文件在 Node.js 中请求外部 js 库

php - 按 ID 更改选定的下拉列表

javascript - 在 zingchart 中动态更改图表主题不起作用

javascript - 如何使用 webpack bundle javascript 文件/Jquery 文件?

javascript - 如何在 JSON 变量永久 JavaScript 数组中进行更改(例如分配新的键和值)?