-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.test.ts
311 lines (264 loc) · 9.49 KB
/
index.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
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
import supertest from "supertest";
import app from "../../../server.js";
import { expectedPlanningPermissionPayload } from "../../../tests/mocks/digitalPlanningDataMocks.js";
import { queryMock } from "../../../tests/graphqlQueryMock.js";
import { $api } from "../../../client/index.js";
import { mockLowcalSession } from "../../../tests/mocks/saveAndReturnMocks.js";
import axios, { type AxiosRequestConfig } from "axios";
import { markSessionAsSubmitted } from "../../saveAndReturn/service/utils.js";
const sessionId = "3188f052-a032-4755-be63-72b0ba497eb6";
const mockPowerAutomateWebhookURL = "http://www.example.com";
const mockPowerAutomateAPIKey = "my-power-automate-api-key";
vi.mock("../../saveAndReturn/service/utils", () => ({
markSessionAsSubmitted: vi.fn(),
}));
vi.mock("../../file/service/uploadFile.js", () => ({
uploadPrivateFile: vi
.fn()
.mockResolvedValue({ fileUrl: "https://my-file-url.com" }),
}));
vi.mock("../../client/index.js");
vi.mock("axios", () => ({
default: vi.fn(),
}));
const mockedAxios = vi.mocked(axios, true);
describe("uploading an application to S3", () => {
beforeEach(() => {
$api.team.getIntegrations = vi.fn().mockResolvedValue({
powerAutomateWebhookURL: mockPowerAutomateWebhookURL,
powerAutomateAPIKey: mockPowerAutomateAPIKey,
});
$api.session.find = vi.fn().mockResolvedValue(mockLowcalSession);
$api.export.digitalPlanningDataPayload = vi
.fn()
.mockResolvedValue(expectedPlanningPermissionPayload);
mockedAxios.mockResolvedValue({ data: { success: true }, status: 200 });
queryMock.mockQuery({
name: "CreateS3Application",
matchOnVariables: false,
data: {
insertS3Application: { id: 1 },
},
});
});
describe("request validation", () => {
it("requires auth", async () => {
await supertest(app)
.post("/upload-submission/barnet")
.send({ payload: { sessionId: "123" } })
.expect(401);
});
it("throws an error if payload is missing", async () => {
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({ payload: null })
.expect(400)
.then((res) => {
expect(res.body).toHaveProperty("issues");
expect(res.body).toHaveProperty("name", "ZodError");
});
});
it("throws an error if powerAutomateWebhookURL is not set", async () => {
$api.team.getIntegrations = vi.fn().mockResolvedValueOnce({
powerAutomateWebhookURL: null,
powerAutomateAPIKey: "some-key",
});
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({
payload: { sessionId },
})
.expect(400)
.then((res) => {
expect(res.body.error).toMatch(
/Upload to S3 is not enabled for this local authority/,
);
});
});
it("throws an error if powerAutomateAPIKey is not set", async () => {
$api.team.getIntegrations = vi.fn().mockResolvedValueOnce({
powerAutomateWebhookURL: "https://www.example.com",
powerAutomateAPIKey: null,
});
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({
payload: { sessionId },
})
.expect(400)
.then((res) => {
expect(res.body.error).toMatch(
/Upload to S3 is not enabled for this local authority/,
);
});
});
});
describe("payload validation", () => {
it("validates statutory payloads", async () => {
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({
payload: { sessionId },
});
// Verify mock session is a statutory application
expect(
mockLowcalSession.data.passport.data?.["application.type"]?.[0],
).toBe("ldc.proposed");
expect($api.export.digitalPlanningDataPayload).toHaveBeenCalledTimes(1);
expect($api.export.digitalPlanningDataPayload).toHaveBeenCalledWith(
sessionId,
false, // Validation not skipped
);
// Validation status passed to webhook
expect(mockedAxios).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
payload: "Validated ODP Schema",
}),
}),
);
});
it("does not validate discretionary payloads", async () => {
// Set up mock discretionary payload
const mockDiscretionarySession = structuredClone(mockLowcalSession);
mockDiscretionarySession.data.passport.data["application.type"][0] =
"reportAPlanningBreach";
$api.session.find = vi
.fn()
.mockResolvedValueOnce(mockDiscretionarySession);
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({
payload: { sessionId },
});
expect($api.export.digitalPlanningDataPayload).toHaveBeenCalledTimes(1);
expect($api.export.digitalPlanningDataPayload).toHaveBeenCalledWith(
sessionId,
true, // Validation skipped
);
// Validation status passed to webhook
expect(mockedAxios).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
payload: "Discretionary",
}),
}),
);
});
});
describe("error handling", () => {
it("throws an error if the webhook request fails", async () => {
mockedAxios.mockRejectedValueOnce(
new Error(
"Something went wrong with the webhook request to Power Automate",
),
);
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({
payload: { sessionId },
})
.expect(500)
.then((res) => {
expect(res.body.error).toMatch(
/Failed to send submission notification/,
);
});
});
it("throws an error if an internal process fails", async () => {
$api.session.find = vi
.fn()
.mockRejectedValueOnce(new Error("Something went wrong!"));
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({
payload: { sessionId },
})
.expect(500)
.then((res) => {
expect(res.body.error).toMatch(/Failed to upload submission to S3/);
});
});
});
describe("success", () => {
beforeEach(() => {
vi.clearAllMocks();
});
const callAPI = async () =>
await supertest(app)
.post("/upload-submission/barnet")
.set({ Authorization: process.env.HASURA_PLANX_API_KEY! })
.send({
payload: { sessionId },
});
it("makes a request to the configured Power Automate webhook", async () => {
await callAPI();
expect(mockedAxios).toHaveBeenCalledOnce();
const request = mockedAxios.mock.calls[0][0] as AxiosRequestConfig;
expect(request.url).toEqual(mockPowerAutomateWebhookURL);
});
it("sets Power Automate API key in request header", async () => {
await callAPI();
expect(mockedAxios).toHaveBeenCalledOnce();
const request = mockedAxios.mock.calls[0][0] as AxiosRequestConfig;
expect(request.headers).toHaveProperty("apiKey", mockPowerAutomateAPIKey);
});
it("generates the expected body for the Power Automate webhook", async () => {
await callAPI();
expect(mockedAxios).toHaveBeenCalledOnce();
const request = mockedAxios.mock.calls[0][0] as AxiosRequestConfig;
expect(request.data).toEqual({
message: "New submission from PlanX",
environment: "staging",
file: "https://my-file-url.com",
payload: "Validated ODP Schema",
service: "Apply for a Lawful Development Certificate",
});
});
it("passes along the correct application environment details", async () => {
vi.stubEnv("APP_ENVIRONMENT", "production");
await callAPI();
expect(mockedAxios).toHaveBeenCalledOnce();
const request = mockedAxios.mock.calls[0][0] as AxiosRequestConfig;
expect(request.data.environment).toEqual("production");
});
it("marks a session as submitted", async () => {
await callAPI();
expect(markSessionAsSubmitted).toHaveBeenCalledOnce();
expect(markSessionAsSubmitted).toHaveBeenCalledWith(sessionId);
});
it("writes an audit record the the s3_applications table", async () => {
await callAPI();
const graphQLCalls = queryMock.getCalls();
expect(graphQLCalls).toEqual(
expect.arrayContaining([
expect.objectContaining({
id: "CreateS3Application",
}),
]),
);
});
it("returns a success message upon completion", async () => {
const res = await callAPI();
expect($api.export.digitalPlanningDataPayload).toHaveBeenCalledWith(
sessionId,
false,
);
expect(res.status).toBe(200);
expect(res.body).toEqual({
message:
"Successfully uploaded submission to S3: https://my-file-url.com",
payload: "Validated ODP Schema",
webhookResponse: 200,
auditEntryId: 1,
});
});
});
});