javascript - 如何模拟节点readline?
问题描述
getUserInput
y
当用户在 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'))
})
}
解决方案
我能够通过添加一个模拟close
函数来解决这个问题。
module.exports = {
createInterface: jest.fn().mockReturnValue({
question: jest.fn().mockImplementationOnce((_questionTest, cb) => cb("y")),
close: jest.fn().mockImplementationOnce(() => undefined)
})
};
推荐阅读
- android - 为什么我的 android studio 看不到我的 gradle 文件?
- java - 为什么有些人使用 PriorityQueue 覆盖比较器函数来实现 minheap,即使 Java 中的 PQ 默认是最小堆?
- android - 如何在 React Native 中添加 Native Bridge Android 的默认值
- android - 如何在 android 的约束布局参数中访问下面的图像
- r - 使用 R 中的 data.table 将空数据帧写入磁盘中的 CSV
- javascript - 如何防止jquery加载已经存在的脚本
- angular - ng2 图表中的散点图
- php - 请求的未知数据库类型枚举,Doctrine\DBAL\Platforms\MySQL57Platform 可能不支持它。Symfony 4
- python - sklearn 错误 - 我已经填写了列的缺失值,但仍然面临以下错误
- javascript - 多维数组 - 递归 / Javascript 简介