我在同一个文件中有两个函数,第一个调用第二个函数,
我想要模拟第二个并测试第一个,
async function test(data) {
try {
const result = await access_to_data_base(data);
return result;
} catch (e) {
return e;
}
}
async function test2(data) {
try {
const test = await test(data);
// deal with the data that we retrieved
const result = treated_data();
return result;
} catch (e) {
return e;
}
}
export.module = {
test,
test2,
}
当我想用模拟数据测试函数test2时,例如它将返回一个假结果,它将返回最终结果或者捕获异常,使用chai和spy
答案 0 :(得分:0)
你不能嘲笑你的功能的原因是因为你的设计耦合不好。您的函数test2
依赖于test
,这使得难以测试。
为了解耦它们,你可以这样做:
async function test(data) {
try {
const result = await access_to_data_base(data);
return result;
} catch (e) {
return e;
}
}
async function test2(results) {
try {
const treatedData = treated_data();
return treatedData;
} catch (e) {
return e;
}
}
export.module = {
test, //then have some higher level function tie them together.
test2,
}
现在,这允许您单独测试函数并传入模拟数据或模拟结果。您还应该将2个功能分成单独的模块,遵循单一责任原则,以实现更高的凝聚力。