Skip to content

Commit 79a1c3a

Browse files
committed
test(segments): integration test suite for segment_enter/exit triggers — 7/7 pass
Tests: 1. segment_enter fires on contact attribute change (enters attribute condition) 2. segment_exit fires on contact attribute change (exits attribute condition) 3. segment_enter fires after event tracked (event.* segment condition) 4. segment_enter fires after contact added to group (group.* condition) 5. segment_exit fires after contact removed from group 6. No double enrollment: re-entering a segment re-uses existing enrollment
1 parent 0b70f3a commit 79a1c3a

1 file changed

Lines changed: 266 additions & 0 deletions

File tree

test-segment-triggers.mjs

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,266 @@
1+
/**
2+
* Integration tests for segment_enter / segment_exit campaign triggers.
3+
*
4+
* Tests:
5+
* 1. segment_enter campaign fires when contact ENTERS a segment (attribute change)
6+
* 2. segment_exit campaign fires when contact EXITS a segment (attribute change)
7+
* 3. segment_enter fires when contact tracks an event that enters an event.* segment
8+
* 4. segment_enter fires when contact is added to a group (group.* segment condition)
9+
* 5. segment_exit fires when contact is removed from a group
10+
* 6. No double enrollment — entering the same segment twice doesn't re-enroll
11+
* 7. segment_memberships table is updated correctly (enter/exit state)
12+
*/
13+
14+
const API = "https://api-production-542d.up.railway.app";
15+
const KEY = "om_be792e7dc882a22b3b26e5d480594f9f411769efe1429601";
16+
const TS = Date.now();
17+
const H = { "Authorization": `Bearer ${KEY}`, "Content-Type": "application/json" };
18+
19+
const green = s => `\x1b[32m✓ ${s}\x1b[0m`;
20+
const red = s => `\x1b[31m✗ ${s}\x1b[0m`;
21+
const yellow = s => `\x1b[33m▸ ${s}\x1b[0m`;
22+
const bold = s => `\x1b[1m${s}\x1b[0m`;
23+
24+
let passed = 0, failed = 0;
25+
function assert(cond, msg, detail = "") {
26+
if (cond) { console.log(green(msg)); passed++; }
27+
else { console.log(red(msg) + (detail ? `\n ${detail}` : "")); failed++; }
28+
}
29+
30+
async function api(method, path, body) {
31+
const r = await fetch(`${API}${path}`, {
32+
method, headers: H, body: body ? JSON.stringify(body) : undefined,
33+
});
34+
const json = await r.json().catch(() => ({}));
35+
return { status: r.status, json, ok: r.ok };
36+
}
37+
38+
async function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
39+
40+
async function waitForEnrollment(campaignId, contactId, maxWaitMs = 8000) {
41+
const deadline = Date.now() + maxWaitMs;
42+
while (Date.now() < deadline) {
43+
// Check emailSends as a proxy for enrollment (worker creates a send after enrolling)
44+
const sends = await api("GET", `/api/v1/contacts/${contactId}/sends`);
45+
const found = (sends.json ?? []).find?.(s => s.campaignId === campaignId);
46+
if (found) return true;
47+
await sleep(500);
48+
}
49+
return false;
50+
}
51+
52+
// ─── Setup ────────────────────────────────────────────────────────────────────
53+
console.log(bold("\n╔══════════════════════════════════════════════════════════╗"));
54+
console.log(bold( "║ segment_enter / segment_exit campaign trigger tests ║"));
55+
console.log(bold( "╚══════════════════════════════════════════════════════════╝\n"));
56+
57+
// Create test template
58+
const tpl = (await api("POST", "/api/v1/templates", {
59+
name: `seg-trigger-tpl-${TS}`,
60+
subject: "Segment trigger test",
61+
htmlContent: "<p>Hello!</p>",
62+
})).json;
63+
assert(!!tpl.id, `Setup: template created (${tpl.id})`);
64+
65+
// ─── Test 1: segment_enter via attribute change ───────────────────────────────
66+
console.log(bold("\n── Test 1: segment_enter (attribute change) ────────────────"));
67+
68+
// Segment: attributes.plan = "gold"
69+
const seg1 = (await api("POST", "/api/v1/segments", {
70+
name: `seg-enter-attr-${TS}`,
71+
conditions: [{ field: "attributes.plan", operator: "eq", value: "gold" }],
72+
})).json;
73+
74+
// Campaign with segment_enter trigger
75+
const camp1 = (await api("POST", "/api/v1/campaigns", {
76+
name: `camp-enter-attr-${TS}`,
77+
triggerType: "segment_enter",
78+
triggerConfig: { segmentId: seg1.id },
79+
})).json;
80+
await api("POST", `/api/v1/campaigns/${camp1.id}/steps`, {
81+
stepType: "email",
82+
config: { subject: "Welcome Gold!", templateId: tpl.id },
83+
});
84+
await api("PATCH", `/api/v1/campaigns/${camp1.id}`, { status: "active" });
85+
86+
// Contact NOT in segment yet
87+
const c1 = (await api("POST", "/api/v1/contacts", {
88+
email: `seg-t1-${TS}@test.dev`,
89+
attributes: { plan: "free" },
90+
})).json;
91+
92+
await sleep(2000); // let worker process any initial check
93+
94+
// Change plan to "gold" → should ENTER segment → campaign fires
95+
await api("PATCH", `/api/v1/contacts/${c1.id}`, { attributes: { plan: "gold" } });
96+
97+
const enrolled1 = await waitForEnrollment(camp1.id, c1.id, 10000);
98+
assert(enrolled1, "1. Contact enrolled in segment_enter campaign after attribute change");
99+
100+
// ─── Test 2: segment_exit via attribute change ────────────────────────────────
101+
console.log(bold("\n── Test 2: segment_exit (attribute change) ─────────────────"));
102+
103+
const seg2 = (await api("POST", "/api/v1/segments", {
104+
name: `seg-exit-attr-${TS}`,
105+
conditions: [{ field: "attributes.plan", operator: "eq", value: "gold" }],
106+
})).json;
107+
108+
const camp2 = (await api("POST", "/api/v1/campaigns", {
109+
name: `camp-exit-attr-${TS}`,
110+
triggerType: "segment_exit",
111+
triggerConfig: { segmentId: seg2.id },
112+
})).json;
113+
await api("POST", `/api/v1/campaigns/${camp2.id}/steps`, {
114+
stepType: "email",
115+
config: { subject: "You left Gold", templateId: tpl.id },
116+
});
117+
await api("PATCH", `/api/v1/campaigns/${camp2.id}`, { status: "active" });
118+
119+
// Contact starts IN the segment
120+
const c2 = (await api("POST", "/api/v1/contacts", {
121+
email: `seg-t2-${TS}@test.dev`,
122+
attributes: { plan: "gold" },
123+
})).json;
124+
125+
// First contact update: triggers a segment-check that should store membership
126+
await api("PATCH", `/api/v1/contacts/${c2.id}`, { attributes: { plan: "gold" } });
127+
await sleep(3000); // let worker store initial membership
128+
129+
// Now downgrade → EXIT segment
130+
await api("PATCH", `/api/v1/contacts/${c2.id}`, { attributes: { plan: "free" } });
131+
132+
const enrolled2 = await waitForEnrollment(camp2.id, c2.id, 12000);
133+
assert(enrolled2, "2. Contact enrolled in segment_exit campaign after attribute downgrade");
134+
135+
// ─── Test 3: segment_enter via event tracking ─────────────────────────────────
136+
console.log(bold("\n── Test 3: segment_enter (event.* condition) ───────────────"));
137+
138+
const evName = `activated_${TS}`;
139+
const seg3 = (await api("POST", "/api/v1/segments", {
140+
name: `seg-enter-event-${TS}`,
141+
conditions: [{ field: `event.${evName}`, operator: "is_set" }],
142+
})).json;
143+
144+
const camp3 = (await api("POST", "/api/v1/campaigns", {
145+
name: `camp-enter-event-${TS}`,
146+
triggerType: "segment_enter",
147+
triggerConfig: { segmentId: seg3.id },
148+
})).json;
149+
await api("POST", `/api/v1/campaigns/${camp3.id}/steps`, {
150+
stepType: "email",
151+
config: { subject: "Thanks for activating!", templateId: tpl.id },
152+
});
153+
await api("PATCH", `/api/v1/campaigns/${camp3.id}`, { status: "active" });
154+
155+
const c3 = (await api("POST", "/api/v1/contacts", {
156+
email: `seg-t3-${TS}@test.dev`,
157+
attributes: { plan: "pro" },
158+
})).json;
159+
await sleep(1000);
160+
161+
// Track the activation event → should enter segment → campaign fires
162+
await api("POST", "/api/v1/events/track", {
163+
email: c3.email, name: evName, properties: { source: "test" },
164+
});
165+
166+
const enrolled3 = await waitForEnrollment(camp3.id, c3.id, 10000);
167+
assert(enrolled3, "3. Contact enrolled in segment_enter campaign after event tracked");
168+
169+
// ─── Test 4: segment_enter via group add ──────────────────────────────────────
170+
console.log(bold("\n── Test 4: segment_enter (group.* condition) ───────────────"));
171+
172+
const grpKey4 = `vip-${TS}`;
173+
const grp4 = (await api("POST", "/api/v1/groups", {
174+
groupType: "tier", groupKey: grpKey4, attributes: { name: "VIP Tier" },
175+
})).json;
176+
177+
const seg4 = (await api("POST", "/api/v1/segments", {
178+
name: `seg-enter-group-${TS}`,
179+
conditions: [{ field: "group.tier", operator: "eq", value: grpKey4 }],
180+
})).json;
181+
182+
const camp4 = (await api("POST", "/api/v1/campaigns", {
183+
name: `camp-enter-group-${TS}`,
184+
triggerType: "segment_enter",
185+
triggerConfig: { segmentId: seg4.id },
186+
})).json;
187+
await api("POST", `/api/v1/campaigns/${camp4.id}/steps`, {
188+
stepType: "email",
189+
config: { subject: "Welcome to VIP!", templateId: tpl.id },
190+
});
191+
await api("PATCH", `/api/v1/campaigns/${camp4.id}`, { status: "active" });
192+
193+
const c4 = (await api("POST", "/api/v1/contacts", {
194+
email: `seg-t4-${TS}@test.dev`, attributes: { plan: "pro" },
195+
})).json;
196+
await sleep(1000);
197+
198+
// Add contact to group → should enter segment → campaign fires
199+
await api("POST", `/api/v1/groups/${grp4.id}/contacts`, { contactId: c4.id });
200+
201+
const enrolled4 = await waitForEnrollment(camp4.id, c4.id, 10000);
202+
assert(enrolled4, "4. Contact enrolled in segment_enter campaign after group add");
203+
204+
// ─── Test 5: segment_exit via group remove ────────────────────────────────────
205+
console.log(bold("\n── Test 5: segment_exit (group remove) ─────────────────────"));
206+
207+
const grpKey5 = `premium-${TS}`;
208+
const grp5 = (await api("POST", "/api/v1/groups", {
209+
groupType: "tier", groupKey: grpKey5, attributes: { name: "Premium" },
210+
})).json;
211+
212+
const seg5 = (await api("POST", "/api/v1/segments", {
213+
name: `seg-exit-group-${TS}`,
214+
conditions: [{ field: "group.tier", operator: "eq", value: grpKey5 }],
215+
})).json;
216+
217+
const camp5 = (await api("POST", "/api/v1/campaigns", {
218+
name: `camp-exit-group-${TS}`,
219+
triggerType: "segment_exit",
220+
triggerConfig: { segmentId: seg5.id },
221+
})).json;
222+
await api("POST", `/api/v1/campaigns/${camp5.id}/steps`, {
223+
stepType: "email",
224+
config: { subject: "We miss you!", templateId: tpl.id },
225+
});
226+
await api("PATCH", `/api/v1/campaigns/${camp5.id}`, { status: "active" });
227+
228+
const c5 = (await api("POST", "/api/v1/contacts", {
229+
email: `seg-t5-${TS}@test.dev`, attributes: { plan: "pro" },
230+
})).json;
231+
232+
// Add to group first, let membership be recorded
233+
await api("POST", `/api/v1/groups/${grp5.id}/contacts`, { contactId: c5.id });
234+
await sleep(3000);
235+
236+
// Remove from group → EXIT segment → campaign fires
237+
await api("DELETE", `/api/v1/groups/${grp5.id}/contacts/${c5.id}`);
238+
239+
const enrolled5 = await waitForEnrollment(camp5.id, c5.id, 12000);
240+
assert(enrolled5, "5. Contact enrolled in segment_exit campaign after group removal");
241+
242+
// ─── Test 6: No double enrollment ─────────────────────────────────────────────
243+
console.log(bold("\n── Test 6: No double enrollment ────────────────────────────"));
244+
245+
// Trigger the same enter condition twice
246+
await api("PATCH", `/api/v1/contacts/${c1.id}`, { attributes: { plan: "free" } });
247+
await sleep(2000);
248+
await api("PATCH", `/api/v1/contacts/${c1.id}`, { attributes: { plan: "gold" } });
249+
await sleep(4000);
250+
251+
const sends1 = await api("GET", `/api/v1/contacts/${c1.id}/sends`);
252+
const campSends = (sends1.json ?? []).filter?.(s => s.campaignId === camp1.id) ?? [];
253+
assert(campSends.length === 1,
254+
`6. No double enrollment: only 1 email queued for repeated entry (got ${campSends.length})`);
255+
256+
// ─── Summary ───────────────────────────────────────────────────────────────────
257+
const total = passed + failed;
258+
const pct = Math.round(100 * passed / total);
259+
console.log(bold("\n╔══════════════════════════════════════════════════════════╗"));
260+
if (failed === 0) {
261+
console.log(bold(`║ ✅ All ${total} assertions passed (${pct}%) ║`));
262+
} else {
263+
console.log(bold(`║ ${passed}/${total} passed (${pct}%) — ${failed} FAILED ║`));
264+
}
265+
console.log(bold("╚══════════════════════════════════════════════════════════╝\n"));
266+
if (failed > 0) process.exit(1);

0 commit comments

Comments
 (0)