-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathemail-service.test.ts
More file actions
219 lines (205 loc) · 9.87 KB
/
Copy pathemail-service.test.ts
File metadata and controls
219 lines (205 loc) · 9.87 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { describe, it, expect, vi } from 'vitest';
import {
EmailService,
LogTransport,
formatAddress,
normalizeMessage,
rowToNormalized,
type EmailPersistence,
} from './email-service.js';
describe('formatAddress', () => {
it('passes through bare addresses', () => {
expect(formatAddress('alice@example.com')).toBe('alice@example.com');
});
it('quotes display names with reserved chars', () => {
expect(formatAddress({ name: 'Alice, CEO', address: 'a@b.com' })).toBe('"Alice, CEO" <a@b.com>');
});
it('does not quote simple display names', () => {
expect(formatAddress({ name: 'Alice', address: 'a@b.com' })).toBe('Alice <a@b.com>');
});
it('rejects malformed addresses', () => {
expect(() => formatAddress('not-an-email')).toThrow(/Invalid email address/);
expect(() => formatAddress({ address: '' })).toThrow(/Invalid email address/);
});
});
describe('normalizeMessage', () => {
it('requires subject', () => {
expect(() => normalizeMessage({ to: 'a@b.com', text: 'hi', subject: '' } as any, 'no@reply.com'))
.toThrow(/subject is required/);
});
it('requires text or html', () => {
expect(() => normalizeMessage({ to: 'a@b.com', subject: 'Hi' } as any, 'no@reply.com'))
.toThrow(/text or html/);
});
it('requires at least one recipient', () => {
expect(() => normalizeMessage({ to: [] as any, subject: 'Hi', text: 'x' }, 'no@reply.com'))
.toThrow(/recipient/);
});
it('requires from when no defaultFrom', () => {
expect(() => normalizeMessage({ to: 'a@b.com', subject: 'Hi', text: 'x' }))
.toThrow(/from address required/);
});
it('canonicalizes recipients and applies defaultFrom', () => {
const msg = normalizeMessage(
{ to: ['a@b.com', { name: 'B', address: 'b@c.com' }], subject: 'Hi', text: 'x' },
{ name: 'No Reply', address: 'no@reply.com' },
);
expect(msg.to).toEqual(['a@b.com', 'B <b@c.com>']);
expect(msg.from).toBe('No Reply <no@reply.com>');
});
});
describe('LogTransport', () => {
it('returns a synthetic Message-ID and logs', async () => {
const logger = { info: vi.fn() };
const t = new LogTransport(logger);
const res = await t.send({ to: ['a@b.com'], from: 'x@y.com', subject: 'Hi', text: 'hello' });
expect(res.messageId).toMatch(/^<dev-/);
expect(logger.info).toHaveBeenCalledWith('[LogTransport] would send email', expect.objectContaining({
subject: 'Hi', to: ['a@b.com'],
}));
});
});
describe('EmailService', () => {
function makePersistence() {
const rows = new Map<string, Record<string, any>>();
const p: EmailPersistence = {
async insert(row) { rows.set(row.id, { ...row }); return { id: row.id }; },
async update(id, patch) {
const cur = rows.get(id);
if (cur) rows.set(id, { ...cur, ...patch });
},
};
return { p, rows };
}
it('sends successfully, persists queued+sent rows', async () => {
const transport = { send: vi.fn(async () => ({ messageId: '<m1@x>' })) };
const { p, rows } = makePersistence();
const svc = new EmailService({ transport, defaultFrom: 'no@reply.com', persistence: p });
const res = await svc.send({ to: 'a@b.com', subject: 'Hi', text: 'hello', relatedObject: 'lead', relatedId: 'L1' });
expect(res.status).toBe('sent');
expect(res.messageId).toBe('<m1@x>');
expect(transport.send).toHaveBeenCalledTimes(1);
const row = rows.get(res.id);
expect(row).toMatchObject({
status: 'sent',
message_id: '<m1@x>',
from_address: 'no@reply.com',
to_addresses: 'a@b.com',
related_object: 'lead',
related_id: 'L1',
attempt_count: 1,
});
expect(typeof row?.sent_at).toBe('string');
});
it('marks failed when transport throws past retry budget', async () => {
const transport = { send: vi.fn(async () => { throw new Error('smtp 421'); }) };
const { p, rows } = makePersistence();
const svc = new EmailService({ transport, defaultFrom: 'no@reply.com', persistence: p, retries: 1 });
const res = await svc.send({ to: 'a@b.com', subject: 'Hi', text: 'x' });
expect(transport.send).toHaveBeenCalledTimes(2); // 1 + 1 retry
expect(res.status).toBe('failed');
expect(res.error).toMatch(/smtp 421/);
expect(rows.get(res.id)).toMatchObject({ status: 'failed', attempt_count: 2 });
});
it('works without persistence', async () => {
const transport = { send: vi.fn(async () => ({ messageId: '<m@x>' })) };
const svc = new EmailService({ transport, defaultFrom: 'no@reply.com' });
const res = await svc.send({ to: 'a@b.com', subject: 'Hi', text: 'x' });
expect(res.status).toBe('sent');
expect(res.id).toMatch(/[0-9a-f-]{30,}/);
});
it('propagates validation errors instead of marking failed', async () => {
const transport = { send: vi.fn(async () => ({ messageId: '<m@x>' })) };
const svc = new EmailService({ transport, defaultFrom: 'no@reply.com' });
await expect(svc.send({ to: 'a@b.com', subject: '', text: 'x' })).rejects.toThrow(/subject is required/);
expect(transport.send).not.toHaveBeenCalled();
});
it('tolerates persistence failures and still delivers', async () => {
const transport = { send: vi.fn(async () => ({ messageId: '<m@x>' })) };
const persistence: EmailPersistence = {
insert: vi.fn(async () => { throw new Error('db down'); }),
update: vi.fn(async () => { throw new Error('db down'); }),
};
const warn = vi.fn();
const svc = new EmailService({
transport, defaultFrom: 'no@reply.com', persistence,
logger: { info: vi.fn(), warn },
});
const res = await svc.send({ to: 'a@b.com', subject: 'Hi', text: 'x' });
expect(res.status).toBe('sent');
expect(warn).toHaveBeenCalledWith(expect.stringContaining('persist failed'), expect.any(Object));
});
// ── Outbox-drain support (sys_email afterInsert) ───────────────────
it('marks its own row managed during send() so the drain hook skips it', async () => {
// The persistence.insert callback fires at exactly the moment the
// afterInsert drain hook would fire — assert the row is flagged managed
// there, and unflagged once send() resolves.
let managedAtInsert: boolean | undefined;
let insertedId: string | undefined;
const transport = { send: vi.fn(async () => ({ messageId: '<m@x>' })) };
let svc!: EmailService;
const persistence: EmailPersistence = {
async insert(row) {
insertedId = String(row.id);
managedAtInsert = svc.isServiceManaged(insertedId);
return { id: row.id };
},
async update() { /* noop */ },
};
svc = new EmailService({ transport, defaultFrom: 'no@reply.com', persistence });
const res = await svc.send({ to: 'a@b.com', subject: 'Hi', text: 'x' });
expect(res.status).toBe('sent');
expect(managedAtInsert).toBe(true); // hook would skip it
expect(svc.isServiceManaged(insertedId!)).toBe(false); // cleared after send
});
it('deliverPersistedRow delivers an existing row WITHOUT inserting a new one', async () => {
const transport = { send: vi.fn(async () => ({ messageId: '<drained@x>' })) };
const { p, rows } = makePersistence();
const insertSpy = vi.spyOn(p, 'insert');
const svc = new EmailService({ transport, persistence: p });
// Simulate an app-inserted outbox row.
const row = {
id: 'row-1', status: 'queued', from_address: 'no@reply.com',
to_addresses: 'a@b.com, c@d.com', subject: 'Drain me', body_text: 'hello',
};
rows.set(row.id, { ...row });
const res = await svc.deliverPersistedRow(row);
expect(res).toMatchObject({ id: 'row-1', status: 'sent', messageId: '<drained@x>' });
expect(transport.send).toHaveBeenCalledTimes(1);
expect(transport.send).toHaveBeenCalledWith(expect.objectContaining({
to: ['a@b.com', 'c@d.com'], from: 'no@reply.com', subject: 'Drain me', text: 'hello',
}));
expect(insertSpy).not.toHaveBeenCalled(); // never inserts a 2nd row
expect(rows.get('row-1')).toMatchObject({ status: 'sent', message_id: '<drained@x>' });
});
it('deliverPersistedRow marks the row failed when it lacks a body', async () => {
const transport = { send: vi.fn(async () => ({ messageId: '<x>' })) };
const { p, rows } = makePersistence();
const svc = new EmailService({ transport, persistence: p });
rows.set('row-2', { id: 'row-2', status: 'queued', from_address: 'a@b.com', to_addresses: 'c@d.com', subject: 'No body' });
const res = await svc.deliverPersistedRow({ id: 'row-2', from_address: 'a@b.com', to_addresses: 'c@d.com', subject: 'No body' });
expect(res.status).toBe('failed');
expect(transport.send).not.toHaveBeenCalled();
expect(rows.get('row-2')).toMatchObject({ status: 'failed' });
});
});
describe('rowToNormalized', () => {
it('reconstructs a message from persisted columns', () => {
const msg = rowToNormalized({
to_addresses: 'a@b.com, "B" <b@c.com>', from_address: 'no@reply.com',
subject: 'Hi', body_text: 'text', body_html: '<p>html</p>',
cc_addresses: 'cc@x.com', bcc_addresses: 'bcc@x.com', reply_to: 'r@x.com',
});
expect(msg).toEqual({
to: ['a@b.com', '"B" <b@c.com>'], from: 'no@reply.com', subject: 'Hi',
text: 'text', html: '<p>html</p>', cc: ['cc@x.com'], bcc: ['bcc@x.com'], replyTo: 'r@x.com',
});
});
it('throws on missing to/from/subject/body', () => {
expect(() => rowToNormalized({ from_address: 'a@b.com', subject: 'x', body_text: 'y' })).toThrow(/to_addresses/);
expect(() => rowToNormalized({ to_addresses: 'a@b.com', subject: 'x', body_text: 'y' })).toThrow(/from_address/);
expect(() => rowToNormalized({ to_addresses: 'a@b.com', from_address: 'c@d.com', body_text: 'y' })).toThrow(/subject/);
expect(() => rowToNormalized({ to_addresses: 'a@b.com', from_address: 'c@d.com', subject: 'x' })).toThrow(/body/);
});
});