Jest-tester för en rabattkalkylator
Utvecklare får omedelbart Jest-tester med full täckning, inklusive gräns- och felfall, istället för att skriva mallkod för hand.
Visa förhandsvisning av in- och utdata
Indata
- Kod att testa
- 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); }
- Programmeringsspråk
- JavaScript
- Testramverk
- Jest
- Täckningsfokus
- Fullständig Täckning (Allt ovan)
- Teststil
- AAA (Organisera-Agera-Bekräfta)
Utdata (utdrag)
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');
});
});