-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.test.ts
More file actions
88 lines (74 loc) · 2.32 KB
/
handler.test.ts
File metadata and controls
88 lines (74 loc) · 2.32 KB
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
const mockQuery = jest.fn();
const mockRelease = jest.fn();
jest.mock('pg', () => ({
Pool: jest.fn().mockImplementation(() => ({
connect: jest.fn().mockResolvedValue({
query: mockQuery,
release: mockRelease,
}),
})),
Client: jest.fn().mockImplementation(() => ({
connect: jest.fn(),
query: mockQuery,
end: jest.fn(),
})),
}));
const createMockContext = () => {
const mockClient = {
query: mockQuery,
release: mockRelease,
};
return {
job: {
jobId: 'test-job-id',
workerId: 'test-worker',
databaseId: 'test-db',
},
pool: {
connect: jest.fn().mockResolvedValue(mockClient),
},
withUserContext: jest.fn(async (_actorId: string | undefined, fn: (client: typeof mockClient) => Promise<unknown>) => {
return fn(mockClient);
}),
log: {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
},
env: {},
};
};
const loadHandler = () => {
const mod = require('../handler');
return mod.default ?? mod;
};
describe('sql-example handler', () => {
beforeEach(() => {
jest.clearAllMocks();
mockQuery.mockReset();
});
it('should execute default query (SELECT version()) when no query provided', async () => {
const handler = loadHandler();
const context = createMockContext();
mockQuery.mockResolvedValueOnce({ rows: [{ version: 'PostgreSQL 15.0' }] });
const result = await handler({}, context);
expect(result.success).toBe(true);
expect(result.message).toBe('Query executed successfully');
expect(context.withUserContext).toHaveBeenCalledWith(undefined, expect.any(Function));
});
it('should execute custom query', async () => {
const handler = loadHandler();
const context = createMockContext();
mockQuery.mockResolvedValueOnce({ rows: [{ count: 5 }] });
const result = await handler({ query: 'SELECT count(*) FROM users' }, context);
expect(result.success).toBe(true);
expect(result.data).toEqual([{ count: 5 }]);
});
it('should pass actor_id to withUserContext', async () => {
const handler = loadHandler();
const context = createMockContext();
mockQuery.mockResolvedValueOnce({ rows: [] });
await handler({ actor_id: 'user-123' }, context);
expect(context.withUserContext).toHaveBeenCalledWith('user-123', expect.any(Function));
});
});