一、JavaScript测试应该做什么
- 单元测试:单元测试是测试单个函数或类的功能是否正确。单元测试应该覆盖代码中的所有路径,以确保代码在所有情况下都能正常工作。
// 单元测试示例
function add(a, b) {
return a + b;
}
test("add() should return the sum of two numbers", () => {
expect(add(1, 2)).toBe(3);
expect(add(-1, 2)).toBe(1);
expect(add(0, 0)).toBe(0);
});
- 集成测试:集成测试是测试多个函数或类组合在一起是否正常工作。集成测试应该覆盖代码中的所有交互,以确保代码在所有情况下都能正常工作。
// 集成测试示例
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
divide(a, b) {
return a / b;
}
}
test("Calculator should add numbers correctly", () => {
const calculator = new Calculator();
expect(calculator.add(1, 2)).toBe(3);
expect(calculator.add(-1, 2)).toBe(1);
expect(calculator.add(0, 0)).toBe(0);
});
test("Calculator should subtract numbers correctly", () => {
const calculator = new Calculator();
expect(calculator.subtract(3, 2)).toBe(1);
expect(calculator.subtract(-1, 2)).toBe(-3);
expect(calculator.subtract(0, 0)).toBe(0);
});
test("Calculator should multiply numbers correctly", () => {
const calculator = new Calculator();
expect(calculator.multiply(2, 3)).toBe(6);
expect(calculator.multiply(-1, 2)).toBe(-2);
expect(calculator.multiply(0, 0)).toBe(0);
});
test("Calculator should divide numbers correctly", () => {
const calculator = new Calculator