summaryrefslogtreecommitdiff
path: root/src/lib/safe-action.test.ts
blob: eee56793222e07630704b4f0160621e147f4e107 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { afterEach, describe, expect, test, vi } from 'vitest';

vi.mock('next-safe-action', () => ({
  DEFAULT_SERVER_ERROR_MESSAGE: 'Internal server error',
  createSafeActionClient: vi.fn((options: unknown) => options),
}));

describe('safe-action', () => {
  afterEach(() => {
    vi.restoreAllMocks();
    vi.resetModules();
  });

  test('returns custom message for ActionError', async () => {
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    const { ActionError, actionClient } = await import('./safe-action');
    const client = actionClient as unknown as {
      handleServerError: (e: Error) => string;
    };

    const message = client.handleServerError(new ActionError('Custom error'));

    expect(message).toBe('Custom error');
    expect(errorSpy).toHaveBeenCalledWith(
      'Failed to execute action:',
      'Custom error',
    );
  });

  test('returns default message for unknown errors', async () => {
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    const { actionClient } = await import('./safe-action');
    const client = actionClient as unknown as {
      handleServerError: (e: Error) => string;
    };

    const message = client.handleServerError(new Error('Unexpected'));

    expect(message).toBe('Internal server error');
    expect(errorSpy).toHaveBeenCalledWith('Failed to execute action:', 'Unexpected');
  });
});