首页 > 解决方案 > 当函数使用 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 中的常见模式吗?

我写的测试太多了吗?有没有更好的方法来编写这些测试?

标签: reactjsjestjs

解决方案


可以在循环中或使用以下方式生成多个测试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"

如果该函数仅接受整数,则可能也需要对其进行保护和测试。


推荐阅读