You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest的toThrow()方法无法正常工作的问题求助

Jest的toThrow()方法无法正常工作的问题求助

各位大佬好,我最近在给计算器功能写Jest测试时卡壳了——明明我的JS代码在处理除以0的情况时,确实抛出了'Division by zero'的错误,但对应的Jest测试就是不通过,实在搞不懂哪里出问题了,来求助大家!

先贴一下相关的Jest测试代码:

describe('operate', () => {
  test("works with addition", () => {
    expect(evaluate_expression("3+5")).toEqual(8);
  });

  test("works with substraction", () => {
    expect(evaluate_expression("128-29")).toEqual(99);
  });

  test("works with multiplication", () => {
    expect(evaluate_expression("25*5")).toEqual(125);
  });

  test("works with division", () => {
    expect(evaluate_expression("990/99")).toEqual(10);
  });

  test("division 0 is handled", () => {
    expect(evaluate_expression("5/0")).toThrow('Division by zero');
  });
});

然后是对应的JavaScript核心代码,重点是evaluate_expression函数里处理除以0的部分(我已经标出来了):

function append_to_display(value) {
  if (start == false)
    document.getElementById('display').value += value;
  else {
    document.getElementById('display').value = value;
  };
};

function calculate() {
  try {
    const expression = document.getElementById('display').value;
    console.log(expression);
    const result = evaluate_expression(expression);
    document.getElementById('display').value = result;
    document.getElementById('current_value').textContent = result;
  } catch (error) {
    document.getElementById('display').value = 'Error';
  }
};

function evaluate_expression(expression) {
  const output_queue = [];
  const operator_stack = [];
  const operators = { '+': 1, '-': 1, '*': 2, '/': 2 };
  const tokens = expression.match(/([0-9]+|\+|\-|\*|\/)/g);

  tokens.forEach(token => {
    if (!isNaN(token)) {
      output_queue.push(parseFloat(token));
    } else if (token in operators) {
      while (
        operator_stack.length > 0 &&
        operators[token] <= operators[operator_stack[operator_stack.length - 1]]
      ) {
        output_queue.push(operator_stack.pop());
      }
      operator_stack.push(token);
    } else {
      throw new Error('Invalid expression');
    }
  });

  while (operator_stack.length > 0) {
    output_queue.push(operator_stack.pop());
  }

  const result_stack = [];
  output_queue.forEach(token => {
    if (!isNaN(token)) {
      result_stack.push(token);
    } else {
      const b = result_stack.pop();
      const a = result_stack.pop();
      switch (token) {
        case '+':
          result_stack.push(a + b);
          break;
        case '-':
          result_stack.push(a - b);
          break;
        case '*':
          result_stack.push(a * b);
          break;
        case '/':
          if (b === 0) {
            throw new Error('Division by zero'); // 这里就是抛出错误的地方,我确认执行到这里时确实会抛错
          }
          result_stack.push(a / b);
          break;
        default:
          throw new Error('Invalid operator');
      }
    }
  });

  if (result_stack.length !== 1) {
    throw new Error('Invalid expression');
  }
}

补充说明下:evaluate_expression()是通过点击计算器的“=”按钮时调用的calculate()函数触发的。我试过在expect后面加rejects,但还是没用,测试依然不通过。有没有大佬能帮我看看问题出在哪呀?

备注:内容来源于stack exchange,提问作者user15970572

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 07:59:33