即使我的JS代码抛出的错误似乎是正确的,它也会失败。相关的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代码:
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'); // HERE IS THE PROBLEM
}
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()
在计算器上单击“=”按钮调用。
JavaScript代码中的确切行如下:
if (b === 0) {
throw new Error('Division by zero'); // HERE IS THE PROBLEM
}
型
我尝试在这里将rejects
附加到expect
,但这不起作用。
1条答案
按热度按时间kd3sttzy1#
为了使用Jest toThrow,你需要向
expect
传递一个函数,也就是说,将你想要测试的代码 Package 在一个函数中。https://jestjs.io/docs/expect#tothrowerror
必须将代码 Package 在函数中,否则错误将不会被捕获,Assert将失败。
字符串