我正在尝试对下面的函数进行单元测试。正如你所看到的,函数的输出依赖于count的值。什么是测试这种类型函数的适当语法和函数?我对Jest和javascript非常陌生。
function greetings(){
if(count == 0){
return "Hello! I am here to assist you in picking your ideal Apple product! YAYYY :D! We can start off by selecting the type of Apple product you wish to buy";
}else if(count == 1){
return "Hello again! Once we get your budget I can narrow down options for your ideal product! Whats your max budget?";
}else if(count == 2){
return "Hello again my friend! Once we get your ideal device size I can narrow down options for your ideal product! Whats your ideal size for this device?";
}
}
这就是我所尝试的
test ('greetings message test', () => {
expect(responses.greetings().toBe("Hello! I am here to assist you in picking your ideal Apple product! YAYYY :D! We can start off by selecting the type of Apple product you wish to buy" || "Hello again! Once we get your budget I can narrow down options for your ideal product! Whats your max budget?" || "Hello again my friend! Once we get your ideal device size I can narrow down options for your ideal product! Whats your ideal size for this device?"))
});
测试失败了。我不确定正确的方法是什么。如果能得到帮助,我将不胜感激。
2条答案
按热度按时间eyh26e7m1#
有多种方法。
第一个是添加一个易于测试的纯函数
第二种方法是将模块作为一个整体进行测试(不那么单一),可以通过在每次测试中重置模块并调用递增/递减函数(或者代码中可以更改计数的任何函数)来将计数设置为预期值
gcmastyq2#
首先我强烈建议其他用户已经说过的(例如,添加一个实际上将计数作为参数的纯函数,这样您就可以轻松地测试它)
BUT
如果由于未知原因您不能严格更改var count
外部的实现,我的建议是以这种方式稍微更改greetings
的实现:然后你可以在测试中使用类似这样的东西: