Spaces:
Running

File size: 3,674 Bytes
f287aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import { describe, expect, it, vi } from 'vitest';
import { AuthApiError, login, preLogin, resolveApiBaseUrl } from '../services/authApi';

const BASE_URL = 'https://example.test/api/v1';

const jsonResponse = (body: unknown, status = 200): Response =>
  new Response(JSON.stringify(body), {
    status,
    headers: { 'Content-Type': 'application/json' },
  });

describe('authApi', () => {
  it('normalizes pre-login response values into typed shape', async () => {
    const fetchMock = vi.fn().mockResolvedValueOnce(
      jsonResponse({
        requiresFarmSelection: false,
        loginResult: {
          token: 'token-1',
          refreshToken: 'refresh-1',
          expiresIn: '3600',
          refreshExpiresIn: '7200',
          user: {
            id: 'user-1',
            email: 'user@example.com',
            role: 'MANAGER',
          },
          requiresOTP: false,
        },
      }),
    );

    const result = await preLogin(
      {
        email: 'user@example.com',
        password: 'StrongPassword123!',
      },
      {
        baseUrl: BASE_URL,
        fetchFn: fetchMock as unknown as typeof fetch,
      },
    );

    expect(result.requiresFarmSelection).toBe(false);
    expect(result.loginResult?.expiresIn).toBe(3600);
    expect(result.loginResult?.refreshExpiresIn).toBe(7200);
    expect(fetchMock).toHaveBeenCalledWith(
      `${BASE_URL}/auth/pre-login`,
      expect.objectContaining({ method: 'POST' }),
    );
  });

  it('throws a clear error when farm selection is required but farms are missing', async () => {
    const fetchMock = vi.fn().mockResolvedValueOnce(
      jsonResponse({
        requiresFarmSelection: true,
        farms: [],
      }),
    );

    await expect(
      preLogin(
        {
          email: 'user@example.com',
          password: 'StrongPassword123!',
        },
        {
          baseUrl: BASE_URL,
          fetchFn: fetchMock as unknown as typeof fetch,
        },
      ),
    ).rejects.toThrow(/No farms were returned/i);
  });

  it('maps backend error payloads to AuthApiError with status and message', async () => {
    const fetchMock = vi.fn().mockResolvedValueOnce(
      jsonResponse(
        {
          statusCode: 400,
          message: ['farmId must be a string', 'farmId should not be empty'],
        },
        400,
      ),
    );

    let error: unknown;
    try {
      await login(
        {
          email: 'user@example.com',
          password: 'StrongPassword123!',
          farmId: 'farm-1',
        },
        {
          baseUrl: BASE_URL,
          fetchFn: fetchMock as unknown as typeof fetch,
        },
      );
    } catch (caught) {
      error = caught;
    }

    expect(error).toBeInstanceOf(Error);
    expect(error).toBeInstanceOf(AuthApiError);
    expect((error as AuthApiError).status).toBe(400);
    expect((error as Error).message).toContain('farmId must be a string');
  });

  it('rejects malformed login payloads when OTP is not required', async () => {
    const fetchMock = vi.fn().mockResolvedValueOnce(
      jsonResponse({
        requiresOTP: false,
        message: 'Login successful',
      }),
    );

    await expect(
      login(
        {
          email: 'user@example.com',
          password: 'StrongPassword123!',
          farmId: 'farm-1',
        },
        {
          baseUrl: BASE_URL,
          fetchFn: fetchMock as unknown as typeof fetch,
        },
      ),
    ).rejects.toThrow(/missing token or user data/i);
  });

  it('resolves API base URL from explicit input before env fallback', () => {
    expect(resolveApiBaseUrl('https://custom.example/api/v1/')).toBe('https://custom.example/api/v1');
  });
});