Skip to content

Commit 58cf4bc

Browse files
author
Alejandro Caicedo
committed
feat: add Supabase integration for products and users
- Implemented ProductSupabaseService for managing products with Supabase. - Added UserSupabaseService for user management using Supabase. - Created tests for product and user services to ensure functionality. - Introduced error handling for Supabase operations. - Updated configuration to include Supabase URL and anon key. - Enhanced storage management using MMKV for Supabase authentication. - Updated package.json to include @supabase/supabase-js dependency.
1 parent 29550b1 commit 58cf4bc

16 files changed

Lines changed: 1323 additions & 1 deletion

File tree

‎.env.example‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
# API Configuration
22
API_URL=https://api.example.com
33

4-
# Service Provider: http | firebase | mock
4+
# Service Provider: http | firebase | supabase | mock
55
SERVICE_PROVIDER=mock
66

77
# Root credentials for mock authentication (optional)
88
ROOT_USERNAME=user@example.com
99
ROOT_PASSWORD=example123
10+
11+
# Supabase (required when SERVICE_PROVIDER=supabase)
12+
SUPABASE_URL=https://your-project-ref.supabase.co
13+
SUPABASE_ANON_KEY=your-anon-key-here
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import React from 'react';
2+
import { fireEvent, render } from '@utils/test-utils';
3+
import { FloatingActionButton } from '@components/core/FloatingActionButton';
4+
5+
describe('FloatingActionButton', () => {
6+
it('debe renderizar correctamente', () => {
7+
const { toJSON } = render(
8+
<FloatingActionButton icon="plus" onPress={jest.fn()} />,
9+
);
10+
expect(toJSON()).toBeTruthy();
11+
});
12+
13+
it('debe ejecutar onPress al presionar', () => {
14+
const onPressMock = jest.fn();
15+
const { getByRole } = render(
16+
<FloatingActionButton icon="plus" onPress={onPressMock} />,
17+
);
18+
19+
fireEvent.press(getByRole('button'));
20+
expect(onPressMock).toHaveBeenCalledTimes(1);
21+
});
22+
23+
it('debe renderizar con tamaño sm', () => {
24+
const { toJSON } = render(
25+
<FloatingActionButton icon="plus" onPress={jest.fn()} size="sm" />,
26+
);
27+
expect(toJSON()).toBeTruthy();
28+
});
29+
30+
it('debe renderizar con tamaño md (default)', () => {
31+
const { toJSON } = render(
32+
<FloatingActionButton icon="plus" onPress={jest.fn()} size="md" />,
33+
);
34+
expect(toJSON()).toBeTruthy();
35+
});
36+
37+
it('debe renderizar con tamaño lg', () => {
38+
const { toJSON } = render(
39+
<FloatingActionButton icon="plus" onPress={jest.fn()} size="lg" />,
40+
);
41+
expect(toJSON()).toBeTruthy();
42+
});
43+
44+
it('debe renderizar con posicion bottom-right (default)', () => {
45+
const { toJSON } = render(
46+
<FloatingActionButton icon="plus" onPress={jest.fn()} position="bottom-right" />,
47+
);
48+
expect(toJSON()).toBeTruthy();
49+
});
50+
51+
it('debe renderizar con posicion bottom-left', () => {
52+
const { toJSON } = render(
53+
<FloatingActionButton icon="plus" onPress={jest.fn()} position="bottom-left" />,
54+
);
55+
expect(toJSON()).toBeTruthy();
56+
});
57+
58+
it('debe renderizar con posicion bottom-center', () => {
59+
const { toJSON } = render(
60+
<FloatingActionButton icon="plus" onPress={jest.fn()} position="bottom-center" />,
61+
);
62+
expect(toJSON()).toBeTruthy();
63+
});
64+
65+
it('debe renderizar con diferentes iconos', () => {
66+
const { toJSON: json1 } = render(
67+
<FloatingActionButton icon="save" onPress={jest.fn()} />,
68+
);
69+
const { toJSON: json2 } = render(
70+
<FloatingActionButton icon="close" onPress={jest.fn()} />,
71+
);
72+
expect(json1()).toBeTruthy();
73+
expect(json2()).toBeTruthy();
74+
});
75+
76+
it('debe tener accessibilityRole button', () => {
77+
const { getByRole } = render(
78+
<FloatingActionButton icon="plus" onPress={jest.fn()} />,
79+
);
80+
expect(getByRole('button')).toBeTruthy();
81+
});
82+
});
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
jest.mock('@modules/supabase', () => ({
2+
supabaseClient: {
3+
from: jest.fn(),
4+
},
5+
manageSupabaseError: jest.fn((e: unknown) => new Error(String(e))),
6+
}));
7+
8+
import productService from '../../../../src/modules/products/infrastructure/product.supabase.service';
9+
import { supabaseClient, manageSupabaseError } from '@modules/supabase';
10+
11+
const mockFrom = supabaseClient.from as jest.Mock;
12+
const mockManageError = manageSupabaseError as jest.Mock;
13+
14+
// Builds a chainable Supabase query mock that resolves to `resolvedValue`
15+
// when awaited directly (getAll/delete) or via .single() (getById/create/update).
16+
function createQueryChain(resolvedValue: unknown) {
17+
const chain: Record<string, jest.Mock> & {
18+
then: (resolve: any, reject?: any) => Promise<unknown>;
19+
} = {
20+
select: jest.fn(),
21+
insert: jest.fn(),
22+
update: jest.fn(),
23+
delete: jest.fn(),
24+
eq: jest.fn(),
25+
ilike: jest.fn(),
26+
or: jest.fn(),
27+
single: jest.fn().mockResolvedValue(resolvedValue),
28+
// Makes the chain itself awaitable (used by getAll and delete)
29+
then(resolve: any, reject?: any) {
30+
return new Promise<unknown>(res => res(resolvedValue)).then(resolve, reject);
31+
},
32+
};
33+
34+
chain.select.mockReturnValue(chain);
35+
chain.insert.mockReturnValue(chain);
36+
chain.update.mockReturnValue(chain);
37+
chain.delete.mockReturnValue(chain);
38+
chain.eq.mockReturnValue(chain);
39+
chain.ilike.mockReturnValue(chain);
40+
chain.or.mockReturnValue(chain);
41+
42+
return chain;
43+
}
44+
45+
const mockProductRow = {
46+
id: '1',
47+
name: 'Producto Test',
48+
description: 'Descripcion test',
49+
price: 15000,
50+
type: 'comida',
51+
created_at: '2024-01-01T00:00:00.000Z',
52+
updated_at: '2024-01-02T00:00:00.000Z',
53+
};
54+
55+
const expectedProduct = {
56+
id: '1',
57+
name: 'Producto Test',
58+
description: 'Descripcion test',
59+
price: 15000,
60+
type: 'comida',
61+
createdAt: new Date('2024-01-01T00:00:00.000Z'),
62+
updatedAt: new Date('2024-01-02T00:00:00.000Z'),
63+
};
64+
65+
describe('ProductSupabaseService', () => {
66+
beforeEach(() => {
67+
jest.clearAllMocks();
68+
mockManageError.mockImplementation((e: unknown) => new Error(String(e)));
69+
});
70+
71+
describe('getAll', () => {
72+
it('debe retornar lista de productos sin filtro', async () => {
73+
const chain = createQueryChain({ data: [mockProductRow], error: null });
74+
mockFrom.mockReturnValue(chain);
75+
76+
const result = await productService.getAll();
77+
78+
expect(result).toEqual([expectedProduct]);
79+
expect(mockFrom).toHaveBeenCalledWith('products');
80+
expect(chain.select).toHaveBeenCalledWith('*');
81+
});
82+
83+
it('debe aplicar filtro ilike cuando hay searchText', async () => {
84+
const chain = createQueryChain({ data: [], error: null });
85+
mockFrom.mockReturnValue(chain);
86+
87+
await productService.getAll({ searchText: 'pizza' });
88+
89+
expect(chain.ilike).toHaveBeenCalledWith('name', '%pizza%');
90+
});
91+
92+
it('no debe aplicar filtro cuando searchText esta vacio', async () => {
93+
const chain = createQueryChain({ data: [mockProductRow], error: null });
94+
mockFrom.mockReturnValue(chain);
95+
96+
await productService.getAll({ searchText: '' });
97+
98+
expect(chain.ilike).not.toHaveBeenCalled();
99+
});
100+
101+
it('debe retornar Error cuando Supabase retorna error', async () => {
102+
const pgError = { message: 'DB error', details: '' };
103+
const chain = createQueryChain({ data: null, error: pgError });
104+
mockFrom.mockReturnValue(chain);
105+
106+
const result = await productService.getAll();
107+
108+
expect(mockManageError).toHaveBeenCalledWith(pgError);
109+
expect(result).toBeInstanceOf(Error);
110+
});
111+
112+
it('debe retornar lista vacia si no hay productos', async () => {
113+
const chain = createQueryChain({ data: [], error: null });
114+
mockFrom.mockReturnValue(chain);
115+
116+
const result = await productService.getAll();
117+
118+
expect(result).toEqual([]);
119+
});
120+
});
121+
122+
describe('getById', () => {
123+
it('debe retornar el producto por id', async () => {
124+
const chain = createQueryChain({ data: mockProductRow, error: null });
125+
mockFrom.mockReturnValue(chain);
126+
127+
const result = await productService.getById('1');
128+
129+
expect(result).toEqual(expectedProduct);
130+
expect(chain.eq).toHaveBeenCalledWith('id', '1');
131+
expect(chain.single).toHaveBeenCalled();
132+
});
133+
134+
it('debe retornar Error cuando el producto no existe', async () => {
135+
const pgError = { message: 'JSON object requested, multiple (or no) rows returned', code: 'PGRST116' };
136+
const chain = createQueryChain({ data: null, error: pgError });
137+
mockFrom.mockReturnValue(chain);
138+
139+
const result = await productService.getById('999');
140+
141+
expect(mockManageError).toHaveBeenCalledWith(pgError);
142+
expect(result).toBeInstanceOf(Error);
143+
});
144+
});
145+
146+
describe('create', () => {
147+
it('debe insertar el producto y retornarlo', async () => {
148+
const chain = createQueryChain({ data: mockProductRow, error: null });
149+
mockFrom.mockReturnValue(chain);
150+
151+
const result = await productService.create({
152+
name: 'Producto Test',
153+
description: 'Descripcion test',
154+
price: 15000,
155+
type: 'comida',
156+
});
157+
158+
expect(result).toEqual(expectedProduct);
159+
expect(chain.insert).toHaveBeenCalledWith({
160+
name: 'Producto Test',
161+
description: 'Descripcion test',
162+
price: 15000,
163+
type: 'comida',
164+
});
165+
});
166+
167+
it('debe usar string vacio como descripcion si no se proporciona', async () => {
168+
const chain = createQueryChain({ data: mockProductRow, error: null });
169+
mockFrom.mockReturnValue(chain);
170+
171+
await productService.create({ name: 'Test', price: 5000, type: 'bebidas' });
172+
173+
expect(chain.insert).toHaveBeenCalledWith(
174+
expect.objectContaining({ description: '' }),
175+
);
176+
});
177+
178+
it('debe retornar Error cuando falla la insercion', async () => {
179+
const pgError = { message: 'insert error', details: '' };
180+
const chain = createQueryChain({ data: null, error: pgError });
181+
mockFrom.mockReturnValue(chain);
182+
183+
const result = await productService.create({ name: 'Test', price: 1000, type: 'otros' });
184+
185+
expect(result).toBeInstanceOf(Error);
186+
});
187+
});
188+
189+
describe('update', () => {
190+
it('debe actualizar el producto con los campos proporcionados', async () => {
191+
const chain = createQueryChain({ data: mockProductRow, error: null });
192+
mockFrom.mockReturnValue(chain);
193+
194+
const result = await productService.update('1', { name: 'Nuevo nombre', price: 20000 });
195+
196+
expect(result).toEqual(expectedProduct);
197+
expect(chain.update).toHaveBeenCalledWith({ name: 'Nuevo nombre', price: 20000 });
198+
expect(chain.eq).toHaveBeenCalledWith('id', '1');
199+
});
200+
201+
it('debe ignorar campos undefined en el payload', async () => {
202+
const chain = createQueryChain({ data: mockProductRow, error: null });
203+
mockFrom.mockReturnValue(chain);
204+
205+
await productService.update('1', { name: 'Nuevo nombre' });
206+
207+
const updatePayload = chain.update.mock.calls[0][0];
208+
expect(Object.keys(updatePayload)).toEqual(['name']);
209+
});
210+
211+
it('debe retornar Error cuando falla la actualizacion', async () => {
212+
const pgError = { message: 'update failed', details: '' };
213+
const chain = createQueryChain({ data: null, error: pgError });
214+
mockFrom.mockReturnValue(chain);
215+
216+
const result = await productService.update('1', { name: 'Test' });
217+
218+
expect(result).toBeInstanceOf(Error);
219+
});
220+
});
221+
222+
describe('delete', () => {
223+
it('debe eliminar el producto y retornar undefined', async () => {
224+
const chain = createQueryChain({ error: null });
225+
mockFrom.mockReturnValue(chain);
226+
227+
const result = await productService.delete('1');
228+
229+
expect(result).toBeUndefined();
230+
expect(chain.delete).toHaveBeenCalled();
231+
expect(chain.eq).toHaveBeenCalledWith('id', '1');
232+
});
233+
234+
it('debe retornar Error cuando falla la eliminacion', async () => {
235+
const pgError = { message: 'delete failed', details: '' };
236+
const chain = createQueryChain({ error: pgError });
237+
mockFrom.mockReturnValue(chain);
238+
239+
const result = await productService.delete('1');
240+
241+
expect(result).toBeInstanceOf(Error);
242+
});
243+
});
244+
});

0 commit comments

Comments
 (0)