如何用jest编写单元测试,以检查是否有返回相同值的else块



我有以下编写的函数,需要用jest:编写单元测试

export const functionToTest=(condition:boolean)=>{
if(condition){
return getDataFromCache()
}
else{
return getDataFromApi()
}
}

我被要求编写单元测试,以确保根据条件调用相应的函数。如果它们不同,我本可以很容易地检查返回值,但由于子函数的返回值是相同的,因此很难根据需要编写单元测试用例。有人知道吗?

我建议编写两个测试,if/else语句中的每个块一个测试:

it("should get data from cache", async () => {
const condition = true;
const result = await functionToTest(condition);
// expect stuff
})
it("should get data from api", async () => {
const condition = false;
const result = await functionToTest(condition);
// expect stuff
})

最新更新