templates2.Store.Nuxt/tests/unit/cart.test.ts
w4c-templates 228f2f01f2
Some checks failed
CI / quality (push) Has been cancelled
chore(template): publish Store.Nuxt
2026-10-11 23:24:30 +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 '#shared/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 }]);
});
});