Skip to main content
Glama
unit-test.ts2.73 kB
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; // ============================================ // Code to Test // ============================================ class Calculator { add(a: number, b: number) { return a + b; } divide(a: number, b: number) { if (b === 0) throw new Error('Cannot divide by zero'); return a / b; } async fetchData(api: () => Promise<any>) { try { return await api(); } catch (e) { return null; } } } // ============================================ // Unit Tests // ============================================ describe('Calculator', () => { let calculator: Calculator; beforeEach(() => { calculator = new Calculator(); }); describe('Math Operations', () => { it('should add two numbers correctly', () => { const result = calculator.add(2, 3); expect(result).toBe(5); }); it('should handle negative numbers', () => { expect(calculator.add(-1, -1)).toBe(-2); expect(calculator.add(-1, 1)).toBe(0); }); it('should divide correctly', () => { expect(calculator.divide(6, 2)).toBe(3); }); it('should throw error when dividing by zero', () => { expect(() => calculator.divide(1, 0)).toThrow('Cannot divide by zero'); }); }); // ============================================ // Mocking Example // ============================================ describe('Async Operations', () => { it('should return data from api', async () => { const mockApi = vi.fn().mockResolvedValue({ id: 1 }); const result = await calculator.fetchData(mockApi); expect(result).toEqual({ id: 1 }); expect(mockApi).toHaveBeenCalledTimes(1); }); it('should return null on failure', async () => { const mockApi = vi.fn().mockRejectedValue(new Error('Fail')); const result = await calculator.fetchData(mockApi); expect(result).toBeNull(); }); }); }); // ============================================ // Snapshot Testing Example // ============================================ describe('Snapshots', () => { it('should match user config snapshot', () => { const config = { theme: 'dark', version: '1.0.0', features: ['a', 'b'], timestamp: new Date('2024-01-01').toISOString(), }; expect(config).toMatchSnapshot(); // Inline snapshot for simpler values expect(config.theme).toMatchInlineSnapshot('"dark"'); }); });

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/millsydotdev/Code-MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server