-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusers.test.ts
More file actions
428 lines (366 loc) · 12.6 KB
/
users.test.ts
File metadata and controls
428 lines (366 loc) · 12.6 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import { afterAll, beforeAll, describe, expect, it } from "@jest/globals";
import { IterableClient } from "../../src/client";
import {
cleanupTestUser,
createTestIdentifiers,
retryWithBackoff,
uniqueId,
waitForUserUpdate,
withTimeout,
} from "../utils/test-helpers";
describe("User Management Integration Tests", () => {
let client: IterableClient;
const { testUserEmail, testUserId } = createTestIdentifiers();
beforeAll(async () => {
client = new IterableClient();
});
afterAll(async () => {
await cleanupTestUser(client, testUserEmail);
client.destroy();
});
it("should create and retrieve a user", async () => {
const userData = {
email: testUserEmail,
userId: testUserId,
dataFields: {
firstName: "Test",
lastName: "User",
testField: "integration-test",
createdAt: new Date().toISOString(),
},
preferUserId: true,
mergeNestedObjects: true,
};
// Create/update user - success is indicated by no exception being thrown
await withTimeout(client.updateUser(userData));
// ✅ VERIFY: User was actually created/updated with correct data
const userResponse = await waitForUserUpdate(client, testUserEmail, {
firstName: "Test",
lastName: "User",
testField: "integration-test",
});
// ✅ VERIFY: User data is correct (already retrieved by waitForUserUpdate)
expect(userResponse.user?.email).toBe(testUserEmail);
expect(userResponse.user?.userId).toBe(testUserId);
});
it("should get user by email using getUserByEmail", async () => {
await withTimeout(
client.updateUser({
email: testUserEmail,
userId: testUserId,
dataFields: { testField: "email-test" },
})
);
// ✅ VERIFY: User update was processed
await waitForUserUpdate(client, testUserEmail, {
testField: "email-test",
});
// ✅ VERIFY: User can be retrieved by email
const userResponse = await withTimeout(
client.getUserByEmail({ email: testUserEmail })
);
expect(userResponse.user?.email).toBe(testUserEmail);
expect(userResponse.user?.dataFields?.testField).toBe("email-test");
});
it("should get user by userId using getUserByUserId", async () => {
await withTimeout(
client.updateUser({
email: testUserEmail,
userId: testUserId,
dataFields: { testField: "userId-test" },
})
);
// ✅ VERIFY: User update was processed
await waitForUserUpdate(client, testUserEmail, {
testField: "userId-test",
});
// ✅ VERIFY: User can be retrieved by userId
const userResponse = await withTimeout(client.getUserByUserId({ userId: testUserId }));
expect(userResponse.user?.userId).toBe(testUserId);
expect(userResponse.user?.email).toBe(testUserEmail);
expect(userResponse.user?.dataFields?.testField).toBe("userId-test");
});
it("should update user data fields", async () => {
const updateTimestamp = Date.now(); // Use numeric timestamp to match existing field type
const updatedData = {
email: testUserEmail,
dataFields: {
firstName: "Updated",
lastName: "Name",
updateTimestamp,
},
mergeNestedObjects: true,
};
// Update user - success indicated by no exception
await withTimeout(client.updateUser(updatedData));
// ✅ VERIFY: Update was actually applied (with eventual consistency)
await waitForUserUpdate(client, testUserEmail, {
firstName: "Updated",
lastName: "Name",
updateTimestamp,
});
});
it("should handle bulk user updates", async () => {
const testId = uniqueId();
const timestamp = Date.now();
const users = [
{
email: `bulk1+${testId}@example.com`,
dataFields: { firstName: "Bulk1", testType: "bulk", timestamp },
},
{
email: `bulk2+${testId}@example.com`,
dataFields: { firstName: "Bulk2", testType: "bulk", timestamp },
},
];
// Bulk update - success indicated by no exception
await withTimeout(client.bulkUpdateUsers({ users }));
try {
// ✅ VERIFY: All users were actually created/updated
await Promise.all(
users.map((user) =>
waitForUserUpdate(client, user.email, {
firstName: user.dataFields.firstName,
testType: "bulk",
timestamp,
})
)
);
} finally {
// Cleanup
await Promise.all(
users.map((user) => cleanupTestUser(client, user.email))
);
}
});
it("should get sent messages for user", async () => {
// First ensure we have a user with some activity
await withTimeout(
client.updateUser({
email: testUserEmail,
dataFields: { messageTest: true },
})
);
const result = await withTimeout(
client.getSentMessages({
email: testUserEmail,
limit: 10,
})
);
expect(result).toBeDefined();
expect(result.messages).toBeDefined();
expect(Array.isArray(result.messages)).toBe(true);
});
it("should get sent messages with filtering", async () => {
// First ensure we have a user with some activity
await withTimeout(
client.updateUser({
email: testUserEmail,
dataFields: { messageFilterTest: true },
})
);
const result = await withTimeout(
client.getSentMessages({
email: testUserEmail,
limit: 5,
messageMedium: "Email",
excludeBlastCampaigns: true,
})
);
expect(result).toBeDefined();
expect(result.messages).toBeDefined();
expect(Array.isArray(result.messages)).toBe(true);
});
it("should get user fields", async () => {
const result = await withTimeout(client.getUserFields());
expect(result).toBeDefined();
expect(result.fields).toBeDefined();
expect(typeof result.fields).toBe("object");
// Should return field definitions for the Iterable project
const fieldCount = Object.keys(result.fields).length;
expect(fieldCount).toBeGreaterThan(0);
// Each field maps to its type as a string
Object.entries(result.fields).forEach(([fieldName, fieldType]) => {
expect(typeof fieldName).toBe("string");
expect(fieldName.length).toBeGreaterThan(0);
expect(typeof fieldType).toBe("string");
expect(fieldType.length).toBeGreaterThan(0);
});
// Should include common user fields
expect(result.fields).toHaveProperty("email");
expect(result.fields).toHaveProperty("userId");
});
it("should delete user by email using deleteUserByEmail", async () => {
const deleteTestId = uniqueId();
const deleteTestEmail = `delete-by-email-test+${deleteTestId}@example.com`;
// Create a user to delete
await withTimeout(
client.updateUser({
email: deleteTestEmail,
dataFields: { deleteTest: true },
})
);
// Wait for user to be created
await waitForUserUpdate(client, deleteTestEmail, { deleteTest: true });
// Delete the user
const deleteResponse = await withTimeout(
client.deleteUserByEmail({ email: deleteTestEmail })
);
expect(deleteResponse.code).toBe("Success");
});
it("should delete user by userId using deleteUserByUserId", async () => {
const deleteTestId = uniqueId();
const deleteTestEmail = `delete-by-userid-test+${deleteTestId}@example.com`;
const deleteTestUserId = `delete-userid-${deleteTestId}`;
// Create a user to delete with preferUserId to ensure userId is primary
await withTimeout(
client.updateUser({
email: deleteTestEmail,
userId: deleteTestUserId,
dataFields: { deleteUserIdTest: true },
preferUserId: true,
})
);
// Wait for user to be created and verify userId is set
await waitForUserUpdate(client, deleteTestEmail, {
deleteUserIdTest: true,
});
// Also verify we can retrieve by userId before deleting (with retry for eventual consistency)
await retryWithBackoff(
async () => {
const userCheck = await client.getUserByUserId({ userId: deleteTestUserId });
if (!userCheck.user?.userId) {
throw new Error("userId not set on user profile yet");
}
expect(userCheck.user.userId).toBe(deleteTestUserId);
},
{
description: `User ${deleteTestUserId} to be retrievable by userId`,
timeoutMs: 30000,
}
);
// Delete the user by userId with retry in case of timing issues
const deleteResponse = await retryWithBackoff(
async () => {
return await client.deleteUserByUserId({ userId: deleteTestUserId });
},
{
description: `Delete user by userId ${deleteTestUserId}`,
timeoutMs: 20000,
shouldRetryOnError: (error: any) => {
// Retry on "User does not exist" errors (might be eventual consistency)
return error?.message?.includes("User does not exist");
},
}
);
expect(deleteResponse.code).toBe("Success");
});
it("should update user email address", async () => {
const updateEmailTestId = uniqueId();
const oldEmail = `old-email-test+${updateEmailTestId}@example.com`;
const newEmail = `new-email-test+${updateEmailTestId}@example.com`;
try {
// Create user with old email
await withTimeout(
client.updateUser({
email: oldEmail,
dataFields: { emailUpdateTest: true },
})
);
// Wait for user to be created
await waitForUserUpdate(client, oldEmail, { emailUpdateTest: true });
// Update the email
const updateResponse = await withTimeout(
client.updateEmail({
currentEmail: oldEmail,
newEmail: newEmail,
})
);
expect(updateResponse.code).toBe("Success");
// Verify user now exists with new email
// Note: There may be some delay in email updates
await new Promise((resolve) => setTimeout(resolve, 2000));
const userResponse = await withTimeout(client.getUserByEmail({ email: newEmail }));
expect(userResponse.user?.email).toBe(newEmail);
} finally {
// Cleanup both possible emails
await cleanupTestUser(client, oldEmail);
await cleanupTestUser(client, newEmail);
}
});
it("should update user subscriptions", async () => {
// First ensure user exists
await withTimeout(
client.updateUser({
email: testUserEmail,
userId: testUserId,
dataFields: { subscriptionTest: true },
})
);
await waitForUserUpdate(client, testUserEmail, { subscriptionTest: true });
// Update subscriptions - this operation overwrites existing subscription data
const updateResponse = await withTimeout(
client.updateUserSubscriptions({
email: testUserEmail,
emailListIds: [], // Empty array for this test
// Note: In a real scenario you'd use actual list/channel/messageType IDs
})
);
expect(updateResponse.code).toBe("Success");
});
it("should merge two user profiles", async () => {
const mergeTestId = uniqueId();
const sourceEmail = `merge-source+${mergeTestId}@example.com`;
const destEmail = `merge-dest+${mergeTestId}@example.com`;
try {
// Create source user
await withTimeout(
client.updateUser({
email: sourceEmail,
dataFields: { mergeTest: true, sourceOnly: "from-source" },
})
);
await waitForUserUpdate(client, sourceEmail, { mergeTest: true });
// Create destination user
await withTimeout(
client.updateUser({
email: destEmail,
dataFields: { mergeTest: true, destOnly: "from-dest" },
})
);
await waitForUserUpdate(client, destEmail, { mergeTest: true });
// Merge source into destination
const mergeResponse = await withTimeout(
client.mergeUsers({
sourceEmail,
destinationEmail: destEmail,
})
);
expect(mergeResponse.code).toBe("Success");
} finally {
await cleanupTestUser(client, sourceEmail);
await cleanupTestUser(client, destEmail);
}
});
it("should update user subscriptions by userId", async () => {
// Ensure user exists with userId
await withTimeout(
client.updateUser({
email: testUserEmail,
userId: testUserId,
dataFields: { subscriptionUserIdTest: true },
})
);
await waitForUserUpdate(client, testUserEmail, {
subscriptionUserIdTest: true,
});
// Update subscriptions using userId
const updateResponse = await withTimeout(
client.updateUserSubscriptions({
userId: testUserId,
emailListIds: [],
})
);
expect(updateResponse.code).toBe("Success");
});
});