reactjs - 当函数使用 if 语句时,如何使用 Jest 在 ReactJs 中正确创建测试
问题描述
A 有一个具有以下功能的 ReactJs 应用程序:
export function setTextoZonaNPS(valorNPS){
if (valorNPS == null) return "Erro"
else if (valorNPS >= 75) return "<span class='verde fonte_60x'>NPS: Zona de Excelência</span>"
else if (valorNPS >= 50) return "<span class='verde fonte_60x'>NPS: Zona de Qualidade</span>"
else if (valorNPS >= 0) return "<span class='laranja fonte_60x'>NPS: Zona de Aperfeiçoamento</span>"
else if (valorNPS < 0) return "<span class='vermelho fonte_60x'>NPS: Zona Crítica</span>"
else return "Erro"
}
我为应用程序编写了一些测试:
test('setTextoZonaNPS_set88String', () => { expect( QuizzesHelper.setTextoZonaNPS("88") ).toMatch(/Excelência/) })
test('setTextoZonaNPS_set88', () => { expect( QuizzesHelper.setTextoZonaNPS(88) ).toMatch(/Excelência/) })
test('setTextoZonaNPS_set47', () => { expect( QuizzesHelper.setTextoZonaNPS(47) ).toMatch(/Qualidade/) })
test('setTextoZonaNPS_set-6', () => { expect( QuizzesHelper.setTextoZonaNPS(-6) ).toMatch(/Aperfeiçoamento/) })
test('setTextoZonaNPS_setString', () => { expect( QuizzesHelper.setTextoZonaNPS("-6") ).toMatch(/Erro/) })
test('setTextoZonaNPS_setUndefined', () => { expect( QuizzesHelper.setTextoZonaNPS(undefined) ).toMatch(/Erro/) })
test('setTextoZonaNPS_setNull', () => { expect( QuizzesHelper.setTextoZonaNPS(null) ).toMatch(/Erro/) })
test('setTextoZonaNPS_setEmpty', () => { expect( QuizzesHelper.setTextoZonaNPS() ).toMatch(/Erro/) })
所有测试均已成功通过。我对我编写的测试和代码有一些疑问。
我需要先检查空值,因为当我使用空值时,它与我使用 0(零)值相同。这是 Javascript 中的常见模式吗?
我写的测试太多了吗?有没有更好的方法来编写这些测试?
解决方案
可以在循环中或使用以下方式生成多个测试test.each
:
const matchMap = [
["88", /Excelência/],
[88, /Excelência/],
...
];
test.each(matchMap)('setTextoZonaNPS with %p', (value, match) => {
expect(QuizzesHelper.setTextoZonaNPS(value)).toMatch(match);
});
或者,如果希望测试在第一个错误时失败,则可以在单个测试中完成:
test('setTextoZonaNPS', () => {
for (const [value, match] of matchMap)
expect(QuizzesHelper.setTextoZonaNPS(value)).toMatch(match);
});
它不测试NaN
. == null
可能不足以检查无效值。NaN
值被覆盖,>= 0
但< 0
一些无效值可能会通过。如果意图是不允许这样做,它可以是:
value = Number.parseFloat(valorNPS);
if (Number.isNaN(valorNPS)) return "Erro"
如果该函数仅接受整数,则可能也需要对其进行保护和测试。
推荐阅读
- python - 如何处理自定义类中具有默认值的关键字标志?
- ruby - random_case(random_name) - 为什么检索随机数据的方法不起作用?
- image - 修改 LatestBlogPosts Umbraco 8
- javascript - 创建事件后无法在组件数据中构建数组
- multithreading - 在 Kotlin 中具有构造函数参数的单例
- php - 将 php 对象反序列化为数组
- html - 调整宽度以使用弹性框填充可用空间
- php - Google Calendar API 服务帐户错误
- c# - 将 Excel 电子表格转换为带有属性的 XML
- javascript - 如何同步外部异步 javascript 下载