如何使用Jest测试含prompt-sync的JS文件?模拟输入方案咨询
解决方案:模拟输入或重构代码实现测试
你有两种可行的方式解决测试时无法模拟输入的问题,具体如下:
1. 直接模拟全局prompt函数
如果不想改动现有代码结构,可以在测试环境中替换全局的prompt方法,让它返回预设的测试数据。以Jest测试框架为例:
// 测试用例中模拟prompt的返回值 test('测试加法运算', () => { // 让prompt第一次返回'3',第二次返回'4' global.prompt = jest.fn() .mockImplementationOnce(() => '3') .mockImplementationOnce(() => '4'); const add = (a, b) => a + b; expect(executeOperation(add)).toBe(7); });
这种方式无需修改业务代码,但缺点是依赖全局对象的模拟,测试耦合度较高。
2. 重构代码解耦输入与业务逻辑
更推荐的方式是拆分代码职责,把获取输入的逻辑和执行运算的逻辑分开,既方便测试,也提升代码可维护性:
// 重构后的代码 const getInputValues = () => { const firstValue = Number(prompt('Enter the first value:')); const secondValue = Number(prompt('Enter the second value:')); return [firstValue, secondValue]; }; const executeOperation = (operation, values) => { // 优先使用传入的测试数据,没有则调用获取输入的方法 const [firstValue, secondValue] = values || getInputValues(); return operation(firstValue, secondValue); }; // 导出函数供测试文件调用 export { executeOperation, getInputValues };
测试时直接传入模拟的数值,完全不需要依赖prompt:
test('测试加法运算(传入模拟数据)', () => { const add = (a, b) => a + b; expect(executeOperation(add, [3, 4])).toBe(7); });
这种方式让代码职责更清晰,后续如果要替换输入方式(比如从表单获取值),只需要修改getInputValues函数即可,无需改动运算逻辑。
内容的提问来源于stack exchange,提问作者Leonardo da Rosa Silveira João
相关产品推荐
相关产品推荐

