-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathproject.controller.cloneTemplate.test.js
More file actions
310 lines (267 loc) · 10.2 KB
/
Copy pathproject.controller.cloneTemplate.test.js
File metadata and controls
310 lines (267 loc) · 10.2 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
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
'use strict';
const mongoose = require('mongoose');
/**
* PROJECT_TEMPLATES — inline copy of just the templates createProject uses.
* We keep this in the test so we never pull in the real @urbackend/common
* (which initialises Redis, BullMQ, GC timers — all blow up in CI).
*/
const PROJECT_TEMPLATES = {
'sdk-kanban': {
name: 'Kanban Board',
description: 'Full-featured Kanban board with drag-and-drop tasks.',
isAuthEnabled: true,
collections: [
{
name: 'boards',
rls: 'private',
model: [{ key: 'title', type: 'String', required: true }],
},
{
name: 'tasks',
rls: 'private',
model: [
{ key: 'boardId', type: 'Ref', required: true },
{ key: 'title', type: 'String', required: true },
{ key: 'status', type: 'String', required: true, default: 'todo' },
],
},
],
},
};
/* ------------------------------------------------------------------ */
/* Real Zod — needed for schema validation inside createProject */
/* ------------------------------------------------------------------ */
const { z } = require('zod');
/* Reconstruct the real createProjectSchema so parse() actually works */
const createProjectSchema = z.object({
name: z.string().min(1, 'Project name is required'),
description: z.string().optional(),
templateId: z.string().optional(),
siteUrl: z.preprocess(
(val) => (val === '' || val === null ? undefined : val),
z
.string()
.url('Invalid Site URL format')
.refine((url) => {
try {
const parsed = new URL(url);
return (
parsed.protocol === 'https:' ||
(parsed.protocol === 'http:' &&
['localhost', '127.0.0.1', '::1'].includes(parsed.hostname))
);
} catch {
return false;
}
}, 'Site URL must use HTTPS (or http://localhost for local development)')
.optional(),
),
});
/* ------------------------------------------------------------------ */
/* Mock @urbackend/common — NO jest.requireActual to avoid side- */
/* effects (Redis, BullMQ queues, GC timers, email service, etc.) */
/* ------------------------------------------------------------------ */
const mockSave = jest.fn();
const mockCountDocuments = jest.fn();
// Minimal Project constructor mock that behaves like a Mongoose model
function MockProject(data) {
Object.assign(this, data);
this._id = data._id || new mongoose.Types.ObjectId();
this.collections = this.collections || [];
this.isAuthEnabled = this.isAuthEnabled || false;
}
MockProject.prototype.save = mockSave;
MockProject.prototype.toObject = function () {
const obj = { ...this };
// Simulate toObject stripping prototype methods
delete obj.save;
delete obj.toObject;
return obj;
};
MockProject.countDocuments = mockCountDocuments;
// For spying / instanceof checks
MockProject.schema = { obj: {} };
jest.mock('@urbackend/common', () => ({
Project: MockProject,
PROJECT_TEMPLATES,
createProjectSchema,
generateApiKey: jest.fn(() => 'test_api_key'),
hashApiKey: jest.fn(() => 'hashed_key'),
encrypt: jest.fn(() => ({ encrypted: 'enc', iv: 'iv', tag: 'tag' })),
markDeveloperOnboardingStep: jest.fn().mockResolvedValue(),
AppError: class AppError extends Error {
constructor(statusCode, message, error = null) {
super(message);
this.name = 'AppError';
this.statusCode = statusCode;
this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
this.error = error || (statusCode >= 500 ? 'Internal Server Error' : 'Error');
this.isOperational = true;
}
},
// Stubs for other imports used at module-level by project.controller.js
Developer: { findById: jest.fn() },
Log: { aggregate: jest.fn() },
getStorage: jest.fn(),
getConnection: jest.fn(),
getCompiledModel: jest.fn(),
QueryEngine: jest.fn(),
storageRegistry: {},
webhookQueue: { add: jest.fn() },
enqueueCollectionCleanup: jest.fn(),
syncCollectionCleanup: jest.fn(),
resolveEffectivePlan: jest.fn(() => ({ name: 'free' })),
deleteProjectByApiKeyCache: jest.fn(),
setProjectById: jest.fn(),
getProjectById: jest.fn(),
deleteProjectById: jest.fn(),
isProjectStorageExternal: jest.fn(() => false),
getBucket: jest.fn(() => 'default'),
getPresignedUploadUrl: jest.fn(),
verifyUploadedFile: jest.fn(),
getPublicIp: jest.fn(),
clearCompiledModel: jest.fn(),
createUniqueIndexes: jest.fn(),
ApiAnalytics: { aggregate: jest.fn() },
MailLog: { aggregate: jest.fn() },
getProjectAccessQuery: jest.fn((userId) => ({
$or: [{ owner: userId }, { 'members.user': userId }],
})),
getProjectRole: jest.fn(),
Invitation: { find: jest.fn() },
sanitizeObjectId: jest.fn((v) => v),
sanitizeNonEmptyString: jest.fn((v) => v),
createCollectionSchema: { parse: jest.fn((v) => v) },
editCollectionSchema: { parse: jest.fn((v) => v) },
updateExternalConfigSchema: { parse: jest.fn((v) => v) },
updateAuthProvidersSchema: { parse: jest.fn((v) => v) },
decrypt: jest.fn(() => 'decrypted'),
getS3CompatibleStorage: jest.fn(),
}));
jest.mock('../utils/emitEvent', () => ({
emitEvent: jest.fn(),
}));
jest.setTimeout(15000);
/* ------------------------------------------------------------------ */
/* Tests */
/* ------------------------------------------------------------------ */
describe('Project Controller - Clone Template', () => {
let req, res;
// Import AFTER mocks are set up
const { createProject } = require('../controllers/project.controller');
beforeEach(() => {
req = {
body: {},
user: { _id: new mongoose.Types.ObjectId(), isVerified: true },
};
res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
};
jest.clearAllMocks();
// Simulate standalone MongoDB (no replica set) — triggers fallback path
jest.spyOn(mongoose, 'startSession').mockRejectedValue(
Object.assign(new Error('Transaction numbers are only allowed on a replica set member or mongos'), { code: 20 })
);
// Mock save to behave like Mongoose save
mockSave.mockImplementation(function () {
this._id = this._id || new mongoose.Types.ObjectId();
return Promise.resolve(this);
});
mockCountDocuments.mockResolvedValue(0);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('should create a project with template configuration', async () => {
req.body = {
name: 'Test Clone Project',
templateId: 'sdk-kanban',
};
await createProject(req, res);
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalled();
const responseObj = res.json.mock.calls[0][0];
expect(responseObj.success).toBe(true);
expect(responseObj.data.name).toBe('Test Clone Project');
expect(responseObj.data.isAuthEnabled).toBe(true);
const collectionNames = responseObj.data.collections.map((c) => c.name);
expect(collectionNames).toContain('boards');
expect(collectionNames).toContain('tasks');
expect(collectionNames).toContain('users');
const boardsCol = responseObj.data.collections.find((c) => c.name === 'boards');
const mode = typeof boardsCol.rls === 'string' ? boardsCol.rls : boardsCol.rls?.mode;
expect(mode).toBe('private');
});
it('should ignore invalid templateId and create a normal project', async () => {
req.body = {
name: 'Normal Project',
templateId: 'invalid-template',
};
await createProject(req, res);
expect(res.status).toHaveBeenCalledWith(201);
const responseObj = res.json.mock.calls[0][0];
expect(responseObj.success).toBe(true);
expect(responseObj.data.name).toBe('Normal Project');
expect(responseObj.data.collections).toHaveLength(0);
expect(responseObj.data.isAuthEnabled).toBeFalsy();
});
it('should create a project without templateId', async () => {
req.body = {
name: 'Blank Project',
};
await createProject(req, res);
expect(res.status).toHaveBeenCalledWith(201);
const responseObj = res.json.mock.calls[0][0];
expect(responseObj.success).toBe(true);
expect(responseObj.data.name).toBe('Blank Project');
expect(responseObj.data.collections).toHaveLength(0);
});
it('should return 400 for missing project name', async () => {
req.body = {};
await createProject(req, res);
expect(res.status).toHaveBeenCalledWith(400);
});
it('should enforce project limit when set', async () => {
req.body = { name: 'Over Limit' };
req.projectLimit = 2;
mockCountDocuments.mockResolvedValue(2);
await createProject(req, res);
expect(res.status).toHaveBeenCalledWith(403);
});
it('should add users collection with auth-enabled template', async () => {
req.body = {
name: 'Auth Template Project',
templateId: 'sdk-kanban',
};
await createProject(req, res);
expect(res.status).toHaveBeenCalledWith(201);
const responseObj = res.json.mock.calls[0][0];
const usersCol = responseObj.data.collections.find((c) => c.name === 'users');
expect(usersCol).toBeDefined();
const usersMode = typeof usersCol.rls === 'string' ? usersCol.rls : usersCol.rls?.mode;
expect(usersMode).toBe('private');
const emailField = usersCol.model.find((f) => f.key === 'email');
const passwordField = usersCol.model.find((f) => f.key === 'password');
expect(emailField).toBeDefined();
expect(passwordField).toBeDefined();
});
it('should create project successfully using transactional path', async () => {
const mockSession = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(),
abortTransaction: jest.fn().mockResolvedValue(),
endSession: jest.fn()
};
mongoose.startSession.mockResolvedValue(mockSession);
req.body = { name: 'Transactional Project' };
await createProject(req, res);
expect(mockSession.startTransaction).toHaveBeenCalled();
expect(mockSession.commitTransaction).toHaveBeenCalled();
expect(mockSession.endSession).toHaveBeenCalled();
expect(res.status).toHaveBeenCalledWith(201);
expect(res.json).toHaveBeenCalledWith(
expect.objectContaining({ success: true, message: 'Project created successfully' })
);
});
});