-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathsaleor-async-webhook.test.ts
283 lines (234 loc) · 9.77 KB
/
saleor-async-webhook.test.ts
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
import { createMocks } from "node-mocks-http";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WebhookError } from "@/handlers/shared";
import { SaleorWebhookValidator } from "@/handlers/shared/saleor-webhook-validator";
import { MockAPL } from "@/test-utils/mock-apl";
import { AsyncWebhookEventType } from "@/types";
import { SaleorAsyncWebhook } from "./saleor-async-webhook";
import { NextJsWebhookHandler, WebhookConfig } from "./saleor-webhook";
const webhookPath = "api/webhooks/product-updated";
const baseUrl = "http://example.com";
describe("Next.js SaleorAsyncWebhook", () => {
const mockAPL = new MockAPL();
afterEach(async () => {
vi.restoreAllMocks();
});
const webhookConfig: WebhookConfig<AsyncWebhookEventType> = {
apl: mockAPL,
event: "PRODUCT_UPDATED",
webhookPath,
query: "subscription { event { ... on ProductUpdated { product { id }}}}",
} as const;
const saleorAsyncWebhook = new SaleorAsyncWebhook(webhookConfig);
describe("getWebhookManifest", () => {
it("should return full path to the webhook route based on given baseUrl", async () => {
expect(saleorAsyncWebhook.getWebhookManifest(baseUrl)).toEqual(
expect.objectContaining({
targetUrl: `${baseUrl}/${webhookPath}`,
}),
);
});
it("should return a valid manifest", async () => {
expect(saleorAsyncWebhook.getWebhookManifest(baseUrl)).toStrictEqual({
asyncEvents: ["PRODUCT_UPDATED"],
isActive: true,
name: "PRODUCT_UPDATED webhook",
targetUrl: "http://example.com/api/webhooks/product-updated",
query: "subscription { event { ... on ProductUpdated { product { id }}}}",
});
});
});
describe("createHandler", () => {
it("validates request before passing it to provided handler function with context", async () => {
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "ok",
context: {
baseUrl: "example.com",
event: "product_updated",
payload: { data: "test_payload" },
schemaVersion: [3, 20],
authData: {
saleorApiUrl: mockAPL.workingSaleorApiUrl,
token: mockAPL.mockToken,
jwks: mockAPL.mockJwks,
appId: mockAPL.mockAppId,
},
},
});
const handler: NextJsWebhookHandler = vi.fn().mockImplementation((_req, res, context) => {
if (context.payload.data === "test_payload") {
res.status(200).end();
return;
}
throw new Error("Test payload has not been passed to handler function");
});
const { req, res } = createMocks();
const wrappedHandler = saleorAsyncWebhook.createHandler(handler);
await wrappedHandler(req, res);
expect(res.statusCode).toBe(200);
expect(handler).toBeCalledTimes(1);
});
it("prevents handler execution when validation fails and returns error", async () => {
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: new Error("Test error"),
});
const handler = vi.fn();
const webhook = new SaleorAsyncWebhook(webhookConfig);
const { req, res } = createMocks();
const wrappedHandler = webhook.createHandler(handler);
await wrappedHandler(req, res);
expect(res.statusCode).toBe(500);
expect(res._getData()).toBe("Unexpected error while handling request");
expect(handler).not.toHaveBeenCalled();
});
describe("when validation throws WebhookError", () => {
it("calls onError and uses formatErrorResponse when provided", async () => {
const webhookError = new WebhookError("Test error", "OTHER");
const formatErrorResponse = vi.fn().mockResolvedValue({
code: 418,
body: "Custom response",
});
const webhook = new SaleorAsyncWebhook({
...webhookConfig,
onError: vi.fn(),
formatErrorResponse,
});
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: webhookError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(webhook.onError).toHaveBeenCalledWith(webhookError, req);
expect(formatErrorResponse).toHaveBeenCalledWith(webhookError, req);
expect(res.statusCode).toBe(418);
expect(res._getData()).toBe("Custom response");
});
it("calls onError and uses default JSON response when formatErrorResponse not provided", async () => {
const webhookError = new WebhookError("Test error", "OTHER");
const webhook = new SaleorAsyncWebhook({
...webhookConfig,
onError: vi.fn(),
});
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: webhookError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(webhook.onError).toHaveBeenCalledWith(webhookError, req);
expect(res.statusCode).toBe(500); // OTHER error is mapped to 500
expect(res._getJSONData()).toEqual({
error: { type: "OTHER", message: "Test error" },
});
});
describe("WebhookError code mapping", () => {
const webhook = new SaleorAsyncWebhook(webhookConfig);
it("should map OTHER error to 500 status code", async () => {
const webhookError = new WebhookError("Internal server error", "OTHER");
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: webhookError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(res.statusCode).toBe(500);
expect(res._getJSONData()).toEqual({
error: {
type: "OTHER",
message: "Internal server error",
},
});
});
it("should map MISSING_HOST_HEADER error to 400 status code", async () => {
const webhookError = new WebhookError("Missing host header", "MISSING_HOST_HEADER");
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: webhookError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(res.statusCode).toBe(400);
expect(res._getJSONData()).toEqual({
error: {
type: "MISSING_HOST_HEADER",
message: "Missing host header",
},
});
});
it("should map NOT_REGISTERED error to 401 status code", async () => {
const webhookError = new WebhookError("Not registered", "NOT_REGISTERED");
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: webhookError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(res.statusCode).toBe(401);
expect(res._getJSONData()).toEqual({
error: {
type: "NOT_REGISTERED",
message: "Not registered",
},
});
});
it("should map WRONG_METHOD error to 405 status code", async () => {
const webhookError = new WebhookError("Wrong HTTP method", "WRONG_METHOD");
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: webhookError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(res.statusCode).toBe(405);
expect(res._getJSONData()).toEqual({
error: {
type: "WRONG_METHOD",
message: "Wrong HTTP method",
},
});
});
});
});
describe("when validation throws generic Error", () => {
const genericError = new Error("Unexpected error");
it("calls onError and uses formatErrorResponse when provided", async () => {
const formatErrorResponse = vi.fn().mockResolvedValue({
code: 500,
body: "Server error",
});
const webhook = new SaleorAsyncWebhook({
...webhookConfig,
onError: vi.fn(),
formatErrorResponse,
});
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: genericError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(webhook.onError).toHaveBeenCalledWith(genericError, req);
expect(formatErrorResponse).toHaveBeenCalledWith(genericError, req);
expect(res.statusCode).toBe(500);
expect(res._getData()).toBe("Server error");
});
it("calls onError and uses default text response when formatErrorResponse not provided", async () => {
const webhook = new SaleorAsyncWebhook({
...webhookConfig,
onError: vi.fn(),
});
vi.spyOn(SaleorWebhookValidator.prototype, "validateRequest").mockResolvedValue({
result: "failure",
error: genericError,
});
const { req, res } = createMocks();
await webhook.createHandler(() => {})(req, res);
expect(webhook.onError).toHaveBeenCalledWith(genericError, req);
expect(res.statusCode).toBe(500);
expect(res._getData()).toBe("Unexpected error while handling request");
});
});
});
});