-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPaymentField.test.ts
More file actions
745 lines (686 loc) · 23 KB
/
PaymentField.test.ts
File metadata and controls
745 lines (686 loc) · 23 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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
import {
ComponentType,
type FormMetadata,
type PaymentFieldComponent
} from '@defra/forms-model'
import { StatusCodes } from 'http-status-codes'
import { ComponentCollection } from '~/src/server/plugins/engine/components/ComponentCollection.js'
import { PaymentField } from '~/src/server/plugins/engine/components/PaymentField.js'
import {
getAnswer,
type Field
} from '~/src/server/plugins/engine/components/helpers/components.js'
import { FormModel } from '~/src/server/plugins/engine/models/FormModel.js'
import { PaymentPreAuthError } from '~/src/server/plugins/engine/pageControllers/errors.js'
import {
type FormContext,
type FormValue,
type PaymentExternalArgs
} from '~/src/server/plugins/engine/types.js'
import {
type FormRequestPayload,
type FormResponseToolkit
} from '~/src/server/routes/types.js'
import { get, post, postJson } from '~/src/server/services/httpService.js'
import { type Services } from '~/src/server/types.js'
import definition from '~/test/form/definitions/blank.js'
import { getFormData, getFormState } from '~/test/helpers/component-helpers.js'
jest.mock('~/src/server/services/httpService.ts')
const mockServices = {
formsService: {
getFormSecret: () => 'secret-value'
}
} as unknown as Services
describe('PaymentField', () => {
let model: FormModel
beforeEach(() => {
model = new FormModel(definition, {
basePath: 'test'
})
})
describe('Defaults', () => {
let def: PaymentFieldComponent
let collection: ComponentCollection
let field: Field
beforeEach(() => {
def = {
title: 'Example payment field',
name: 'myComponent',
type: ComponentType.PaymentField,
options: {
amount: 100,
description: 'Test payment description'
}
} satisfies PaymentFieldComponent
collection = new ComponentCollection([def], { model })
field = collection.fields[0]
})
describe('Schema', () => {
it('uses component title as label as default', () => {
const { formSchema } = collection
const { keys } = formSchema.describe()
expect(keys).toHaveProperty(
'myComponent',
expect.objectContaining({
flags: expect.objectContaining({
label: 'Example payment field'
})
})
)
})
it('uses component name as keys', () => {
const { formSchema } = collection
const { keys } = formSchema.describe()
expect(field.keys).toEqual(['myComponent'])
expect(field.collection).toBeUndefined()
for (const key of field.keys) {
expect(keys).toHaveProperty(key)
}
})
it('is required by default', () => {
const { formSchema } = collection
const { keys } = formSchema.describe()
expect(keys).toHaveProperty(
'myComponent',
expect.objectContaining({
keys: expect.objectContaining({
amount: expect.objectContaining({
flags: expect.objectContaining({
presence: 'required'
})
})
})
})
)
})
it('adds errors for empty value', () => {
const payment = {
paymentId: '',
reference: '',
amount: 0,
description: '',
uuid: '',
formId: '',
isLivePayment: false
}
const result = collection.validate(
getFormData(payment as unknown as FormValue)
)
const errors = result.errors ?? []
expect(errors[0]).toEqual(
expect.objectContaining({
text: 'Enter myComponent.paymentId'
})
)
expect(errors[1]).toEqual(
expect.objectContaining({
text: 'Enter myComponent.reference'
})
)
expect(errors[2]).toEqual(
expect.objectContaining({
text: 'Enter myComponent.description'
})
)
expect(errors[3]).toEqual(
expect.objectContaining({
text: 'Enter myComponent.uuid'
})
)
expect(errors[4]).toEqual(
expect.objectContaining({
text: 'Enter myComponent.formId'
})
)
expect(errors[5]).toEqual(
expect.objectContaining({
text: 'Select myComponent.preAuth'
})
)
})
it('adds errors for invalid values', () => {
const result1 = collection.validate(getFormData(['invalid']))
const result2 = collection.validate(
// @ts-expect-error - Allow invalid param for test
getFormData({ unknown: 'invalid' })
)
expect(result1.errors).toBeTruthy()
expect(result2.errors).toBeTruthy()
})
})
describe('State', () => {
const paymentForState = {
paymentId: 'payment-id',
reference: 'payment-ref',
amount: 150,
description: 'payment description',
uuid: 'ee501106-4ce1-4947-91a7-7cc1a335ccd8',
formId: 'formid',
isLivePayment: false
}
it('returns text from state', () => {
const state1 = getFormState(paymentForState as unknown as FormValue)
const state2 = getFormState(null)
const answer1 = getAnswer(field, state1)
const answer2 = getAnswer(field, state2)
expect(answer1).toBe('£150.00 - payment description')
expect(answer2).toBe('')
})
})
describe('View model', () => {
it('sets Nunjucks component defaults', () => {
const viewModel = field.getViewModel(getFormData(undefined))
expect(viewModel).toEqual(
expect.objectContaining({
label: { text: def.title },
name: 'myComponent',
id: 'myComponent',
amount: '£100.00',
attributes: {},
description: 'Test payment description'
})
)
})
it('sets Nunjucks component values', () => {
const paymentForViewModel = {
paymentId: 'payment-id',
reference: 'payment-ref',
uuid: 'ee501106-4ce1-4947-91a7-7cc1a335ccd8',
formId: 'formid',
amount: 100,
description: 'Test payment description',
isLivePayment: false
} as unknown as FormValue
const viewModel = field.getViewModel(getFormData(paymentForViewModel))
expect(viewModel).toEqual(
expect.objectContaining({
label: { text: def.title },
name: 'myComponent',
id: 'myComponent',
amount: '£100.00',
attributes: {},
description: 'Test payment description'
})
)
})
})
describe('AllPossibleErrors', () => {
it('should return errors', () => {
const errors = field.getAllPossibleErrors()
expect(errors.baseErrors).not.toBeEmpty()
expect(errors.advancedSettingsErrors).toBeEmpty()
})
})
})
describe('dispatcher and onSubmit', () => {
const def = {
title: 'Example payment field',
name: 'myComponent',
type: ComponentType.PaymentField,
options: {
amount: 100,
description: 'Test payment description'
}
} satisfies PaymentFieldComponent
const collection = new ComponentCollection([def], { model })
const paymentField = collection.fields[0] as PaymentField
paymentField.model = { services: mockServices } as unknown as FormModel
describe('dispatcher', () => {
it('should create payment and redirect to gov pay', async () => {
const mockYarSet = jest.fn()
const mockRequest = {
server: {
plugins: {
// eslint-disable-next-line no-useless-computed-key
['forms-engine-plugin']: {
baseUrl: 'base-url'
}
}
},
yar: {
set: mockYarSet
}
} as unknown as FormRequestPayload
const mockH = {
redirect: jest
.fn()
.mockReturnValueOnce({ code: jest.fn().mockReturnValueOnce('ok') })
} as unknown as FormResponseToolkit
const args = {
controller: {
model: {
formId: 'formid',
basePath: 'base-path',
name: 'PaymentModel',
services: mockServices
},
getState: jest
.fn()
.mockResolvedValueOnce({ $$__referenceNumber: 'pay-ref-123' })
},
component: paymentField,
sourceUrl: 'http://localhost:3009/test-payment',
isLive: false,
isPreview: true
} as unknown as PaymentExternalArgs
// @ts-expect-error - partial mock
jest.mocked(postJson).mockResolvedValueOnce({
payload: {
state: {
status: 'created'
},
payment_id: 'new-payment-id',
_links: {
next_url: {
href: '/next-url'
}
}
}
})
const res = await PaymentField.dispatcher(mockRequest, mockH, args)
expect(res).toBe('ok')
expect(mockYarSet).toHaveBeenCalledWith(expect.any(String), {
amount: 100,
componentName: 'myComponent',
description: 'Test payment description',
failureUrl: 'http://localhost:3009/test-payment',
formId: 'formid',
isLivePayment: false,
paymentId: 'new-payment-id',
reference: 'pay-ref-123',
returnUrl: 'base-url/base-path/summary',
uuid: expect.any(String)
})
})
it('should redirect to summary if payment is already pre-authorised', async () => {
const mockRedirectCode = jest.fn().mockReturnValueOnce('redirected')
const mockH = {
redirect: jest.fn().mockReturnValueOnce({ code: mockRedirectCode })
} as unknown as FormResponseToolkit
const mockRequest = {
server: {
plugins: {
// eslint-disable-next-line no-useless-computed-key
['forms-engine-plugin']: {
baseUrl: 'base-url'
}
}
},
yar: {
set: jest.fn()
}
} as unknown as FormRequestPayload
const args = {
controller: {
model: {
formId: 'formid',
basePath: 'base-path',
name: 'PaymentModel',
services: mockServices
},
getState: jest.fn().mockResolvedValueOnce({
$$__referenceNumber: 'pay-ref-123',
myComponent: {
paymentId: 'existing-payment-id',
amount: 100,
description: 'Test payment',
preAuth: {
status: 'success',
createdAt: '2026-01-29T12:00:00.000Z'
}
}
})
},
component: paymentField,
sourceUrl: 'http://localhost:3009/test-payment',
isLive: false,
isPreview: true
} as unknown as PaymentExternalArgs
const res = await PaymentField.dispatcher(mockRequest, mockH, args)
expect(res).toBe('redirected')
expect(mockH.redirect).toHaveBeenCalledWith(
'base-url/base-path/summary'
)
expect(mockRedirectCode).toHaveBeenCalledWith(303)
expect(postJson).not.toHaveBeenCalled()
})
it('should display error if create payment fails (e.g. network or bad api key) - test payment', async () => {
const mockYarSet = jest.fn()
const mockYarFlash = jest.fn()
const mockRequest = {
server: {
plugins: {
// eslint-disable-next-line no-useless-computed-key
['forms-engine-plugin']: {
baseUrl: 'base-url'
}
}
},
yar: {
set: mockYarSet,
flash: mockYarFlash
},
url: {
href: '/here'
}
} as unknown as FormRequestPayload
const mockH = {
redirect: jest
.fn()
.mockReturnValueOnce({ code: jest.fn().mockReturnValueOnce('ok') })
} as unknown as FormResponseToolkit
const args = {
controller: {
model: {
formId: 'formid',
basePath: 'base-path',
name: 'PaymentModel',
services: mockServices
},
getState: jest
.fn()
.mockResolvedValueOnce({ $$__referenceNumber: 'pay-ref-123' })
},
component: paymentField,
sourceUrl: 'http://localhost:3009/test-payment',
isLive: false,
isPreview: true
} as unknown as PaymentExternalArgs
jest.mocked(postJson).mockImplementationOnce(() => {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw { output: { statusCode: StatusCodes.UNAUTHORIZED } }
})
const res = await PaymentField.dispatcher(mockRequest, mockH, args)
expect(res).toBe('ok')
expect(mockYarSet).not.toHaveBeenCalled()
expect(mockYarFlash).toHaveBeenCalledWith(
'COMPONENT_STATE_ERROR',
{
href: '#myComponent',
name: 'myComponent',
text: 'Add a valid test API key before you can preview the payment journey.'
},
true
)
})
it('should display error if create payment fails (e.g. network or bad api key) - live payment', async () => {
const mockYarSet = jest.fn()
const mockYarFlash = jest.fn()
const mockRequest = {
server: {
plugins: {
// eslint-disable-next-line no-useless-computed-key
['forms-engine-plugin']: {
baseUrl: 'base-url'
}
}
},
yar: {
set: mockYarSet,
flash: mockYarFlash
},
url: {
href: '/here'
}
} as unknown as FormRequestPayload
const mockH = {
redirect: jest
.fn()
.mockReturnValueOnce({ code: jest.fn().mockReturnValueOnce('ok') })
} as unknown as FormResponseToolkit
const args = {
controller: {
model: {
formId: 'formid',
basePath: 'base-path',
name: 'PaymentModel',
services: mockServices
},
getState: jest
.fn()
.mockResolvedValueOnce({ $$__referenceNumber: 'pay-ref-123' })
},
component: paymentField,
sourceUrl: 'http://localhost:3009/test-payment',
isLive: true,
isPreview: false
} as unknown as PaymentExternalArgs
jest.mocked(postJson).mockImplementationOnce(() => {
// eslint-disable-next-line @typescript-eslint/only-throw-error
throw { output: { statusCode: StatusCodes.UNAUTHORIZED } }
})
const res = await PaymentField.dispatcher(mockRequest, mockH, args)
expect(res).toBe('ok')
expect(mockYarSet).not.toHaveBeenCalled()
expect(mockYarFlash).toHaveBeenCalledWith(
'COMPONENT_STATE_ERROR',
{
href: '#myComponent',
name: 'myComponent',
text: 'There is a problem and we cannot take a payment. Contact us (details in the footer of this form) or save your progress and return to the form later.'
},
true
)
})
})
describe('onSubmit', () => {
it('should throw if missing state', async () => {
const mockRequest = {} as unknown as FormRequestPayload
const error = await paymentField
.onSubmit(
mockRequest,
{} as FormMetadata,
{ state: {} } as FormContext
)
.catch((e: unknown) => e)
expect(error).toBeInstanceOf(PaymentPreAuthError)
expect((error as PaymentPreAuthError).component).toBe(paymentField)
expect((error as PaymentPreAuthError).userMessage).toBe(
'Complete the payment to continue'
)
})
it('should ignore if our state says payment already captured', async () => {
const mockRequest = {} as unknown as FormRequestPayload
await paymentField.onSubmit(
mockRequest,
{} as FormMetadata,
{
state: {
myComponent: {
capture: {
status: 'success'
},
paymentId: 'payment-id',
amount: 123,
description: 'Payment desc'
}
}
} as unknown as FormContext
)
expect(get).not.toHaveBeenCalled()
expect(post).not.toHaveBeenCalled()
})
it('should mark payment already captured according to gov pay', async () => {
const mockRequest = {} as unknown as FormRequestPayload
jest
.mocked(get)
// @ts-expect-error - partial mock
.mockResolvedValueOnce({
payload: { amount: 10000, state: { status: 'success' } }
})
await paymentField.onSubmit(
mockRequest,
{} as FormMetadata,
{
state: {
myComponent: {
paymentId: 'payment-id',
amount: 100,
description: 'Payment desc',
isLivePayment: false,
formId: 'formid'
}
}
} as unknown as FormContext
)
expect(get).toHaveBeenCalled()
expect(post).not.toHaveBeenCalled()
})
it('should throw if bad status', async () => {
const mockRequest = {} as unknown as FormRequestPayload
jest
.mocked(get)
// @ts-expect-error - partial mock
.mockResolvedValueOnce({
payload: { amount: 10000, state: { status: 'bad' } }
})
const error = await paymentField
.onSubmit(
mockRequest,
{} as FormMetadata,
{
state: {
myComponent: {
paymentId: 'payment-id',
amount: 100,
description: 'Payment desc',
isLivePayment: false,
formId: 'formid'
}
}
} as unknown as FormContext
)
.catch((e: unknown) => e)
expect(error).toBeInstanceOf(PaymentPreAuthError)
expect((error as PaymentPreAuthError).component).toBe(paymentField)
expect((error as PaymentPreAuthError).userMessage).toBe(
'Your payment authorisation has expired. Please add your payment details again.'
)
})
it('should throw if error during capture', async () => {
const mockRequest = {} as unknown as FormRequestPayload
jest
.mocked(get)
// @ts-expect-error - partial mock
.mockResolvedValueOnce({
payload: { amount: 10000, state: { status: 'capturable' } }
})
// @ts-expect-error - partial mock
jest.mocked(post).mockResolvedValueOnce({ res: { statusCode: 400 } })
const error = await paymentField
.onSubmit(
mockRequest,
{} as FormMetadata,
{
state: {
myComponent: {
paymentId: 'payment-id',
amount: 123,
description: 'Payment desc',
isLivePayment: false,
formId: 'formid'
}
}
} as unknown as FormContext
)
.catch((e: unknown) => e)
expect(error).toBeInstanceOf(PaymentPreAuthError)
expect((error as PaymentPreAuthError).component).toBe(paymentField)
expect((error as PaymentPreAuthError).userMessage).toBe(
'There was a problem and your form was not submitted. Try submitting the form again.'
)
})
it('should throw if amount mismatch', async () => {
const mockRequest = {} as unknown as FormRequestPayload
jest
.mocked(get)
// @ts-expect-error - partial mock
.mockResolvedValueOnce({
payload: { amount: 5000, state: { status: 'capturable' } }
})
// @ts-expect-error - partial mock
jest.mocked(post).mockResolvedValueOnce({ res: { statusCode: 200 } })
const error = await paymentField
.onSubmit(
mockRequest,
{} as FormMetadata,
{
state: {
myComponent: {
paymentId: 'payment-id',
amount: 123,
description: 'Payment desc',
isLivePayment: false,
formId: 'formid'
}
}
} as unknown as FormContext
)
.catch((e: unknown) => e)
expect(error).toBeInstanceOf(PaymentPreAuthError)
expect((error as PaymentPreAuthError).component).toBe(paymentField)
expect((error as PaymentPreAuthError).userMessage).toBe(
'The pre-authorised payment amount is somehow different from that requested. Try adding payment details again.'
)
})
it('should capture payment if no errors', async () => {
const mockRequest = {} as unknown as FormRequestPayload
jest
.mocked(get)
// @ts-expect-error - partial mock
.mockResolvedValueOnce({
payload: { amount: 10000, state: { status: 'capturable' } }
})
// @ts-expect-error - partial mock
jest.mocked(post).mockResolvedValueOnce({ res: { statusCode: 200 } })
await paymentField.onSubmit(
mockRequest,
{} as FormMetadata,
{
state: {
myComponent: {
paymentId: 'payment-id',
amount: 123,
description: 'Payment desc',
isLivePayment: false,
formId: 'formid'
}
}
} as unknown as FormContext
)
expect(get).toHaveBeenCalled()
expect(post).toHaveBeenCalled()
})
})
describe('getFormValue', () => {
it('should return undefined', () => {
expect(paymentField.getFormValue({})).toBeUndefined()
})
it('should return value', () => {
const payment = {
paymentId: 'payment-id',
amount: 123,
description: 'Payment desc',
isLivePayment: false,
formId: 'formid'
}
expect(paymentField.getFormValue(payment)).toEqual(payment)
})
})
describe('isState', () => {
it('should return false if not valid state', () => {
expect(paymentField.isState({})).toBe(false)
})
it('should return value', () => {
const payment = {
paymentId: 'payment-id',
amount: 123,
description: 'Payment desc',
isLivePayment: false,
formId: 'formid'
}
expect(paymentField.isState(payment)).toBe(true)
})
})
})
})