templates2.Store.Next/tests/unit/cart.test.ts
w4c-templates bb75e7c742
Some checks are pending
CI / quality (push) Waiting to run
chore(template): publish Store.Next
2026-10-11 23:24:13 +03:00

60 lines
2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from 'vitest';
import { parseVariants, unitPrice, validateLines, type ProductLike } from '@/lib/cart';
const products: ProductLike[] = [
{ id: 'p1', name: 'Tee', price: 2900, stock: 5, variants: [{ name: 'M', priceDelta: 0 }, { name: 'L', priceDelta: 200 }] },
{ id: 'p2', name: 'Mug', price: 1800, stock: 1 },
];
describe('validateLines (cart totals)', () => {
it('sums quantity × price and applies variant price deltas', () => {
const result = validateLines(
[
{ productId: 'p1', variant: 'L', quantity: 2 },
{ productId: 'p2', quantity: 1 },
],
products,
);
expect(result.ok).toBe(true);
if (result.ok) {
// (2900 + 200) * 2 + 1800 = 8000
expect(result.total).toBe(8000);
expect(result.items).toHaveLength(2);
}
});
it('rejects an empty cart', () => {
expect(validateLines([], products)).toEqual({ ok: false, error: 'Your cart is empty.' });
});
it('rejects an unknown product', () => {
const r = validateLines([{ productId: 'nope', quantity: 1 }], products);
expect(r.ok).toBe(false);
});
it('rejects an unknown variant', () => {
const r = validateLines([{ productId: 'p1', variant: 'XXL', quantity: 1 }], products);
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error).toContain('XXL');
});
it('rejects a quantity above stock', () => {
const r = validateLines([{ productId: 'p2', quantity: 99 }], products);
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error).toContain('Only 1 left');
});
});
describe('unitPrice / parseVariants', () => {
it('adds the variant delta to the base price', () => {
expect(unitPrice(products[0], 'M')).toBe(2900);
expect(unitPrice(products[0], 'L')).toBe(3100);
expect(unitPrice(products[0])).toBe(2900);
});
it('ignores malformed variant data', () => {
expect(parseVariants('nope')).toEqual([]);
expect(parseVariants([{ name: 'S' }, { nope: true }])).toEqual([{ name: 'S', priceDelta: 0 }]);
});
});