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();
});
};
我需要为
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'))
})
}
jest.mock('readline')
?在被测试的代码中它是如何导入的? - jonrsharpejest.mock('moduleName')
放置在与require/import语句相同的作用域中。" 不要把它放在规范内部。 - jonrsharpereadline
,并将readline
作为参数接受(带有默认值),这样您就可以轻松地在测试中传递一个假的readline
。 - Madara's Ghost