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 的 readline
的 getUserInput
创建一个测试。
目前我尝试了以下但没有成功,得到:
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/