Unit Tests with Vitest

Setup

Example

npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom vite-tsconfig-paths

Example output

added 112 packages in 14s

vitest.config.mts

vitest.config.mts

import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
  plugins: [tsconfigPaths(), react()],
  test: { environment: 'jsdom', setupFiles: ['./vitest.setup.ts'] },
});

A Unit Test

// lib/cart.test.ts
import { describe, expect, it } from 'vitest';
import { cartTotal } from './cart';

describe('cartTotal', () => {
  it('adds items and applies the coupon', () => {
    const items = [{ price: 499, qty: 2 }, { price: 1299, qty: 1 }];
    expect(cartTotal(items, 'SAVE10')).toEqual({ subtotal: 2297, discount: 230, delivery: 0, total: 2067 });
  });

  it('charges delivery below ₹499', () => {
    expect(cartTotal([{ price: 199, qty: 1 }]).delivery).toBe(40);
  });
});

Example

npx vitest run

Example output

 ✓ lib/cart.test.ts (2 tests) 3ms

 Test Files  1 passed (1)
      Tests  2 passed (2)
   Duration  412ms

The Code Under Test

Example

lib/cart.ts with a mini expect so you can see the tests pass here:

type Line = { price: number; qty: number };

export function cartTotal(items: Line[], coupon?: string) {
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const discount = coupon === 'SAVE10' ? Math.round(subtotal * 0.1) : 0;
  const delivery = subtotal - discount >= 499 ? 0 : 40;
  return { subtotal, discount, delivery, total: subtotal - discount + delivery };
}

function it(name: string, fn: () => void) {
  try { fn(); console.log('✓ ' + name); } catch (e) { console.log('✗ ' + name + ': ' + (e as Error).message); }
}
function expectEqual(actual: unknown, expected: unknown) {
  const a = JSON.stringify(actual), b = JSON.stringify(expected);
  if (a !== b) throw new Error('expected ' + b + ' but got ' + a);
}

it('adds items and applies the coupon', () =>
  expectEqual(cartTotal([{ price: 499, qty: 2 }, { price: 1299, qty: 1 }], 'SAVE10'), { subtotal: 2297, discount: 230, delivery: 0, total: 2067 }));
it('charges delivery below ₹499', () => expectEqual(cartTotal([{ price: 199, qty: 1 }]).delivery, 40));
it('ignores unknown coupons', () => expectEqual(cartTotal([{ price: 100, qty: 1 }], 'FREE100').discount, 0));

Output

✓ adds items and applies the coupon
✓ charges delivery below ₹499
✓ ignores unknown coupons