js开关声明单元测试

时间:2018-05-03 15:03:39

标签: javascript testing enzyme jest

我有这样的util函数:

export const selectOperator = (operator, n1, n2) => {
    let result;

    switch(operator) {
        case '+':
            result = n1 + n2;
            console.log(result)
        case "-":
            result = n1 - n2;
        case "*":
            result = n1 * n2;
        case "/":
            result = n1 / n2;
    }

    return result;
}

我试图像这样测试:

it('should select the right case based on the operator', () => {
  const operators = ['+', '/', '-', '*']
  const numA = 10
  const numB = 5

  operators.forEach(el => {
    if(el == '+'){
      //selectOperator(el, numA, numB).toEqual(12)
      console.log(selectOperator('+', 10, 5))
    }
    if(el == '-'){
      //selectOperator(el, numA, numB).toEqual(12)
      //console.log(selectOperator(el, numA, numB))
    }
    if(el == '/'){
      //selectOperator(el, numA, numB).toEqual(12)
      //console.log(selectOperator(el, numA, numB))
    }
    if(el == '*'){
      //selectOperator(el, numA, numB).toEqual(12)
      //console.log(selectOperator(el, numA, numB))
    }
  })
})

util函数内的控制台返回15并且这是正确的,但是测试中的控制台返回2(看起来它正在划分10/5)

1 个答案:

答案 0 :(得分:1)

你的switch \ case中没有'break'语句,所以当你在util中记录你的结果时结果是正确的,但结果因缺少break而不断变化。

您的代码应为:

export const selectOperator = (operator, n1, n2) => {
  let result;

  switch(operator) {
      case '+':
          result = n1 + n2;
          console.log(result)
          break;
      case "-":
          result = n1 - n2;
          break;
      case "*":
          result = n1 * n2;
          break;
      case "/":
          result = n1 / n2;
          break;
  }

  return result;
}