1 import sendgrid from "@sendgrid/mail"
2 import { SendgridNotificationService } from "../../src/services/sendgrid"
3
4 jest.mock("@sendgrid/mail", () => ({
5 __esModule: true,
6 default: {
7 setApiKey: jest.fn(),
8 send: jest.fn().mockResolvedValue([{ statusCode: 202 }, {}]),
9 },
10 }))
11
12 jest.mock("@medusajs/framework/utils", () => ({
13 AbstractNotificationProviderService: class {},
14 MedusaError: class MedusaError extends Error {
15 static Types = {
16 INVALID_DATA: "invalid_data",
17 UNEXPECTED_STATE: "unexpected_state",
18 }
19 type: string
20 constructor(type: string, message: string) {
21 super(message)
22 this.type = type
23 }
24 },
25 }), { virtual: true })
26
27 const mockSend = sendgrid.send as jest.MockedFunction<typeof sendgrid.send>
28
29 jest.setTimeout(100000)
30
31 describe("SendgridNotificationService - personalizations", () => {
32 let service: SendgridNotificationService
33
34 beforeEach(() => {
35 jest.clearAllMocks()
36 service = new SendgridNotificationService(
37 { logger: console as any },
38 { api_key: "test-api-key", from: "sender@example.com" }
39 )
40 })
41
42 it("passes provider_data.personalizations directly to sendgrid and omits top-level to", async () => {
43 await service.send({
44 to: "recipient@example.com",
45 channel: "email",
46 template: "some-template",
47 provider_data: {
48 personalizations: [
49 {
50 to: [{ email: "recipient@example.com" }],
51 customArgs: { campaign_id: "abc123", source: "welcome-flow" },
52 },
53 ],
54 },
55 })
56
57 expect(mockSend).toHaveBeenCalledTimes(1)
58 const message = mockSend.mock.calls[0][0] as any
59 expect(message).not.toHaveProperty("to")
60 expect(message.personalizations).toEqual([
61 {
62 to: [{ email: "recipient@example.com" }],
63 customArgs: { campaign_id: "abc123", source: "welcome-flow" },
64 },
65 ])
66 })
67
68 it("uses top-level to and omits personalizations when provider_data.personalizations is absent", async () => {
69 await service.send({
70 to: "recipient@example.com",
71 channel: "email",
72 template: "some-template",
73 })
74
75 expect(mockSend).toHaveBeenCalledTimes(1)
76 const message = mockSend.mock.calls[0][0] as any
77 expect(message.to).toEqual("recipient@example.com")
78 expect(message).not.toHaveProperty("personalizations")
79 })
80
81 it("falls back to top-level to when provider_data.personalizations is an empty array", async () => {
82 await service.send({
83 to: "recipient@example.com",
84 channel: "email",
85 template: "some-template",
86 provider_data: {
87 personalizations: [],
88 },
89 })
90
91 expect(mockSend).toHaveBeenCalledTimes(1)
92 const message = mockSend.mock.calls[0][0] as any
93 expect(message.to).toEqual("recipient@example.com")
94 expect(message).not.toHaveProperty("personalizations")
95 })
96 })
97
98 // Note: This test hits the sendgrid service, and it is mainly meant to be run manually after setting all the envvars below.
99 // We could also setup a sink email service to test this automatically, but it is not necessary for the time being.
100 describe.skip("Sendgrid notification provider", () => {
101 let sendgridService: SendgridNotificationService
102 let emailTemplate = ""
103 let emailContent = ""
104 let to = ""
105 beforeAll(() => {
106 sendgridService = new SendgridNotificationService(
107 {
108 logger: console as any,
109 },
110 {
111 api_key: process.env.SENDGRID_TEST_API_KEY ?? "",
112 from: process.env.SENDGRID_TEST_FROM ?? "",
113 }
114 )
115
116 emailTemplate = process.env.SENDGRID_TEST_TEMPLATE ?? ""
117 emailContent = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html dir="ltr" xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office"><head><meta charset="UTF-8"></head><body>Welcome to medusa</body></html>`
118 to = process.env.SENDGRID_TEST_TO ?? ""
119 })
120
121 it("sends an email with the specified template", async () => {
122 const resp = await sendgridService.send({
123 to,
124 channel: "email",
125 template: emailTemplate,
126 data: {
127 username: "john-doe",
128 },
129 })
130
131 expect(resp).toEqual({})
132 })
133
134 it("sends an email with the specified email body", async () => {
135 const resp = await sendgridService.send({
136 to,
137 channel: "email",
138 template: "signup-template",
139 content: {
140 subject: "It's a test",
141 html: emailContent,
142 },
143 data: {
144 username: "john-doe",
145 },
146 })
147
148 expect(resp).toEqual({})
149 })
150
151 it("throws an exception if the subject is not present for html content", async () => {
152 const error = await sendgridService
153 .send({
154 to,
155 template: "signup-template",
156 channel: "email",
157 content: { html: emailContent },
158 data: {
159 username: "john-doe",
160 },
161 })
162 .catch((e) => e)
163
164 expect(error.message).toEqual(
165 "Failed to send email: 400 - The subject is required. You can get around this requirement if you use a template with a subject defined or if every personalization has a subject defined."
166 )
167 })
168
169 it("throws an exception if the template does not exist", async () => {
170 const error = await sendgridService
171 .send({
172 to,
173 channel: "email",
174 template: "unknown-template",
175 data: {
176 username: "john-doe",
177 },
178 })
179 .catch((e) => e)
180
181 expect(error.message).toEqual(
182 "Failed to send email: 400 - The template_id must be a valid GUID, you provided 'unknown-template'."
183 )
184 })
185 it("throws an exception if the to email is not valid", async () => {
186 const error = await sendgridService
187 .send({
188 to: "not-email",
189 channel: "email",
190 template: emailTemplate,
191 data: {
192 username: "john-doe",
193 },
194 })
195 .catch((e) => e)
196
197 expect(error.message).toEqual(
198 "Failed to send email: 400 - Does not contain a valid address."
199 )
200 })
201 })