面向折扣计算器的 Jest 测试
开发者可即时获得全覆盖的 Jest 测试,包括边界和错误情况,无需手写样板代码。
查看输入和输出预览
输入
- 待测试代码
- function calculateDiscount(price, userTier, couponCode) { let discount = 0; if (userTier === 'gold') discount += 0.15; else if (userTier === 'silver') discount += 0.10; if (couponCode === 'SAVE20') discount += 0.20; if (discount > 0.5) discount = 0.5; if (price < 0) throw new Error('Price cannot be negative'); return +(price * (1 - discount)).toFixed(2); }
- 编程语言
- JavaScript
- 测试框架
- Jest
- 覆盖重点
- 全面覆盖(以上所有)
- 测试风格
- AAA(准备-执行-断言)
输出(节选)
describe('calculateDiscount', () => {
it('applies gold tier discount', () => {
// Arrange
const price = 100;
// Act
const result = calculateDiscount(price, 'gold', null);
// Assert
expect(result).toBe(85);
});
it('caps total discount at 50%', () => {
expect(calculateDiscount(100, 'gold', 'SAVE20')).toBe(65);
});
it('throws on negative price', () => {
expect(() => calculateDiscount(-5, 'gold', null)).toThrow('Price cannot be negative');
});
});