diff --git a/src/server/plugins/engine/components/AutocompleteField.test.ts b/src/server/plugins/engine/components/AutocompleteField.test.ts index a8de95dbc..a1bbe2c60 100644 --- a/src/server/plugins/engine/components/AutocompleteField.test.ts +++ b/src/server/plugins/engine/components/AutocompleteField.test.ts @@ -135,6 +135,17 @@ describe.each([ expect(result.errors).toBeUndefined() }) + it('adds the select error for an invalid optional value', () => { + const collectionOptional = new ComponentCollection( + [{ ...def, options: { required: false } }], + { model } + ) + + const result = collectionOptional.validate(getFormData('invalid')) + + expect(result.errors?.[0].text).toBe(`Select ${lowerFirst(def.title)}`) + }) + it('is configured with autocomplete suggestions', () => { const { formSchema } = collection const { keys } = formSchema.describe() diff --git a/src/server/plugins/engine/components/AutocompleteField.ts b/src/server/plugins/engine/components/AutocompleteField.ts index dd4115bb9..436a7b46f 100644 --- a/src/server/plugins/engine/components/AutocompleteField.ts +++ b/src/server/plugins/engine/components/AutocompleteField.ts @@ -50,11 +50,17 @@ export class AutocompleteField extends SelectField { } getValidationMessagesOverride(translator: Translator) { - const { customValidationMessages } = this.options + const { customValidationMessages, required } = this.options + + // An optional field keeps the global messages, as the constructor does + if (required === false) { + return null + } + const { t } = translator const defaults = { - 'any.required': buildValidationMessages(t).objectRequired, - 'any.only': buildValidationMessages(t).objectRequired + 'any.required': buildValidationMessages(t).required, + 'any.only': buildValidationMessages(t).required } return { diff --git a/src/server/plugins/engine/components/ComponentCollection.ts b/src/server/plugins/engine/components/ComponentCollection.ts index b25dbad44..774f09fc9 100644 --- a/src/server/plugins/engine/components/ComponentCollection.ts +++ b/src/server/plugins/engine/components/ComponentCollection.ts @@ -222,7 +222,7 @@ export class ComponentCollection { overrideParentTitle( formSchema: joi.ObjectSchema, - translator: Translator | undefined + translator: Translator ) { // Add parent field title to collection field errors return formSchema.error((errors) => { @@ -249,8 +249,14 @@ export class ComponentCollection { (item) => item.name === key ) - // Update error with child label - if (child && (!error.local.label || error.local.label === 'value')) { + // Update error with child label. A composite field child has a key as + // its title, so that the label shows in the language of the translator + if (child && parent?.collection) { + error.local.label = translator.t(child.title) + } else if ( + child && + (!error.local.label || error.local.label === 'value') + ) { error.local.label = child.title } @@ -261,10 +267,8 @@ export class ComponentCollection { } // Update error with parent title - if (translator && parent) { + if (parent) { error.local.title ??= getTranslatedLabel(parent.def, translator) - } else { - error.local.title ??= parent?.label } return error @@ -277,73 +281,59 @@ export class ComponentCollection { */ validate( value: FormPayload = {}, - translator?: Translator + translator: Translator = this.model.createTranslator() ): FormValidationResult { - const messages = translator - ? buildLanguageMessages(translator.t) - : undefined + const messages = buildLanguageMessages(translator.t) - // When translating, override Joi labels (and custom schema messages where - // needed) so #label/#title in message templates resolve in the correct language. + // Override Joi labels (and custom schema messages where needed) so that + // #label/#title in message templates resolve in the language of the translator let schema = this.formSchema // Add parent field title to collection field errors schema = this.overrideParentTitle(schema, translator) - if (translator) { - const { t } = translator - const labelOverrides: Record = {} - - for (const field of this.fields) { - if (field.collection) { - // Composite field: translate each sub-field's label using the key constant - // (e.g. 'components.addressField.line1' → "Llinell cyfeiriad 1") and apply - // any field-type-specific message overrides (e.g. objectMissing for dates). - const messagesOverride = - field.getValidationMessagesOverride(translator) - for (const subField of field.collection.fields) { - const translatedSubLabel = t(subField.title) || subField.label - let patchedSchema = subField.formSchema.label(translatedSubLabel) - const subFieldMessages = messagesOverride - ? messagesOverride[subField.name] - : undefined - if (subFieldMessages) { - patchedSchema = patchedSchema.messages(subFieldMessages) - } - labelOverrides[subField.name] = patchedSchema - } - } else { - const fieldDef = field.def - const translatedLabel = getTranslatedLabel(fieldDef, translator) - const messagesOverride = - field.getValidationMessagesOverride(translator) - let patchedSchema = field.formSchema - if (translatedLabel && translatedLabel !== field.label) { - patchedSchema = patchedSchema.label(translatedLabel) - } - const fieldMessages = messagesOverride - ? messagesOverride[field.name] + const { t } = translator + + for (const field of this.fields) { + if (field.collection) { + // Composite field: translate each sub-field's label using the key constant + // (e.g. 'components.addressField.line1' → "Llinell cyfeiriad 1") and apply + // any field-type-specific message overrides (e.g. objectMissing for dates). + const messagesOverride = field.getValidationMessagesOverride(translator) + for (const subField of field.collection.fields) { + const translatedSubLabel = t(subField.title) || subField.label + let patchedSchema = subField.formSchema.label(translatedSubLabel) + const subFieldMessages = messagesOverride + ? messagesOverride[subField.name] : undefined - if (fieldMessages) { - patchedSchema = patchedSchema.messages(fieldMessages) - } - if (patchedSchema !== field.formSchema) { - labelOverrides[field.name] = patchedSchema + if (subFieldMessages) { + patchedSchema = patchedSchema.messages(subFieldMessages) } + schema = this.replaceFieldSchema(schema, subField.name, patchedSchema) + } + } else { + const fieldDef = field.def + const translatedLabel = getTranslatedLabel(fieldDef, translator) + const messagesOverride = field.getValidationMessagesOverride(translator) + let patchedSchema = field.formSchema + if (translatedLabel && translatedLabel !== field.label) { + patchedSchema = patchedSchema.label(translatedLabel) + } + const fieldMessages = messagesOverride + ? messagesOverride[field.name] + : undefined + if (fieldMessages) { + patchedSchema = patchedSchema.messages(fieldMessages) + } + if (patchedSchema !== field.formSchema) { + schema = this.replaceFieldSchema(schema, field.name, patchedSchema) } - } - - if (Object.keys(labelOverrides).length) { - schema = schema.keys(labelOverrides) } } - const result = schema.validate(value, { - ...opts, - ...(messages && { messages }) - }) + const result = schema.validate(value, { ...opts, messages }) const details = result.error?.details - const language = translator?.language + const { language } = translator return { value: (result.value ?? {}) as typeof value, @@ -352,6 +342,18 @@ export class ComponentCollection { } } + /** + * Replace the schema of one field in the form schema. The field keeps its + * position, so that the errors stay in the same order as the page + */ + private replaceFieldSchema( + formSchema: ObjectSchema, + name: string, + fieldSchema: joi.Schema + ) { + return formSchema.fork(name, () => fieldSchema) + } + /** * Helper to get errors from all fields */ diff --git a/src/server/plugins/engine/components/DatePartsField.test.ts b/src/server/plugins/engine/components/DatePartsField.test.ts index be478aa9d..0a26ed1ed 100644 --- a/src/server/plugins/engine/components/DatePartsField.test.ts +++ b/src/server/plugins/engine/components/DatePartsField.test.ts @@ -175,11 +175,9 @@ describe('DatePartsField', () => { ) expect(result1.errors).toBeUndefined() - // Sub-field title is a key constant; error text uses the raw key until - // request-time resolution is wired in (Task 8 / Task 9). expect(result2.errors).toEqual([ expect.objectContaining({ - text: 'Example date parts field must include a components.dateField.month' + text: 'Example date parts field must include a month' }) ]) }) @@ -244,16 +242,15 @@ describe('DatePartsField', () => { }) ) - // Sub-field titles are key constants; error text uses raw keys until Task 9. expect(result.errors).toEqual([ expect.objectContaining({ - text: 'Example date parts must include a components.dateField.day' + text: 'Example date parts must include a day' }), expect.objectContaining({ - text: 'Example date parts must include a components.dateField.month' + text: 'Example date parts must include a month' }), expect.objectContaining({ - text: 'Example date parts must include a components.dateField.year' + text: 'Example date parts must include a year' }) ]) }) diff --git a/src/server/plugins/engine/components/EastingNorthingField.test.ts b/src/server/plugins/engine/components/EastingNorthingField.test.ts index d624f2f33..2070eae6e 100644 --- a/src/server/plugins/engine/components/EastingNorthingField.test.ts +++ b/src/server/plugins/engine/components/EastingNorthingField.test.ts @@ -603,8 +603,7 @@ describe('EastingNorthingField', () => { errors: [ expect.objectContaining({ text: expect.stringMatching( - /components\.eastingNorthingField\.easting for .* must be between 1000 and 60000/ - // Sub-field title is a key constant; resolved at request time (Task 8/9). + /Easting for .* must be between 1000 and 60000/ ) }) ] @@ -623,8 +622,7 @@ describe('EastingNorthingField', () => { errors: [ expect.objectContaining({ text: expect.stringMatching( - /components\.eastingNorthingField\.easting for .* must be between 1000 and 60000/ - // Sub-field title is a key constant; resolved at request time (Task 8/9). + /Easting for .* must be between 1000 and 60000/ ) }) ] @@ -660,8 +658,7 @@ describe('EastingNorthingField', () => { errors: [ expect.objectContaining({ text: expect.stringMatching( - /components\.eastingNorthingField\.northing for .* must be between 1000 and 1200000/ - // Sub-field title is a key constant; resolved at request time (Task 8/9). + /Northing for .* must be between 1000 and 1200000/ ) }) ] @@ -680,8 +677,7 @@ describe('EastingNorthingField', () => { errors: [ expect.objectContaining({ text: expect.stringMatching( - /components\.eastingNorthingField\.northing for .* must be between 1000 and 1200000/ - // Sub-field title is a key constant; resolved at request time (Task 8/9). + /Northing for .* must be between 1000 and 1200000/ ) }) ] @@ -712,8 +708,7 @@ describe('EastingNorthingField', () => { errors: [ expect.objectContaining({ text: expect.stringMatching( - /components\.eastingNorthingField\.easting for .* must be between 1 and 6 digits/ - // Sub-field title is a key constant; resolved at request time (Task 8/9). + /Easting for .* must be between 1 and 6 digits/ ) }) ] @@ -732,8 +727,7 @@ describe('EastingNorthingField', () => { errors: [ expect.objectContaining({ text: expect.stringMatching( - /components\.eastingNorthingField\.northing for .* must be between 1 and 7 digits/ - // Sub-field title is a key constant; resolved at request time (Task 8/9). + /Northing for .* must be between 1 and 7 digits/ ) }) ] @@ -793,7 +787,6 @@ describe('EastingNorthingField', () => { expect.objectContaining({ text: expect.stringMatching( /myComponent failed custom validation because/ - // Sub-field title is a key constant; resolved at request time (Task 8/9). ) }) ] diff --git a/src/server/plugins/engine/components/LatLongField.test.ts b/src/server/plugins/engine/components/LatLongField.test.ts index 4d49a0b14..bb4854447 100644 --- a/src/server/plugins/engine/components/LatLongField.test.ts +++ b/src/server/plugins/engine/components/LatLongField.test.ts @@ -684,8 +684,7 @@ describe('LatLongField', () => { }), errors: [ expect.objectContaining({ - text: 'components.latLongField.latitude must have no more than 7 decimal places' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Latitude must have no more than 7 decimal places' }) ] } @@ -702,8 +701,7 @@ describe('LatLongField', () => { }), errors: [ expect.objectContaining({ - text: 'components.latLongField.longitude must have no more than 7 decimal places' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Longitude must have no more than 7 decimal places' }) ] } @@ -781,8 +779,7 @@ describe('LatLongField', () => { }), errors: [ expect.objectContaining({ - text: 'components.latLongField.latitude must have no more than 7 decimal places' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Latitude must have no more than 7 decimal places' }) ] } @@ -812,8 +809,7 @@ describe('LatLongField', () => { }), errors: [ expect.objectContaining({ - text: 'components.latLongField.longitude must have no more than 7 decimal places' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Longitude must have no more than 7 decimal places' }) ] } diff --git a/src/server/plugins/engine/components/LocationFieldBase.ts b/src/server/plugins/engine/components/LocationFieldBase.ts index 7d7c367c1..838b85e32 100644 --- a/src/server/plugins/engine/components/LocationFieldBase.ts +++ b/src/server/plugins/engine/components/LocationFieldBase.ts @@ -151,9 +151,9 @@ export abstract class LocationFieldBase extends FormComponent { const config = this.getValidationConfig(translator) const defaults = { 'any.required': - config.requiredMessage ?? buildValidationMessages(t).objectRequired, + config.requiredMessage ?? buildValidationMessages(t).required, 'string.empty': - config.requiredMessage ?? buildValidationMessages(t).objectRequired, + config.requiredMessage ?? buildValidationMessages(t).required, 'string.pattern.base': config.patternErrorMessage } diff --git a/src/server/plugins/engine/components/MonthYearField.test.ts b/src/server/plugins/engine/components/MonthYearField.test.ts index 75e8354ee..6d625b41c 100644 --- a/src/server/plugins/engine/components/MonthYearField.test.ts +++ b/src/server/plugins/engine/components/MonthYearField.test.ts @@ -145,10 +145,9 @@ describe('MonthYearField', () => { ) expect(result1.errors).toBeUndefined() - // Sub-field title is a key constant; error text uses raw key until Task 9. expect(result2.errors).toEqual([ expect.objectContaining({ - text: 'Example month/year field must include a components.monthYearField.year' + text: 'Example month/year field must include a year' }) ]) }) @@ -210,13 +209,12 @@ describe('MonthYearField', () => { }) ) - // Sub-field titles are key constants; error text uses raw keys until Task 9. expect(result.errors).toEqual([ expect.objectContaining({ - text: 'Example month/year must include a components.monthYearField.month' + text: 'Example month/year must include a month' }), expect.objectContaining({ - text: 'Example month/year must include a components.monthYearField.year' + text: 'Example month/year must include a year' }) ]) }) @@ -237,13 +235,12 @@ describe('MonthYearField', () => { }) ) - // Sub-field titles are key constants; error text uses raw keys until Task 9. expect(result.errors).toEqual([ expect.objectContaining({ - text: 'Example month/year field must include a components.monthYearField.month' + text: 'Example month/year field must include a month' }), expect.objectContaining({ - text: 'Example month/year field must include a components.monthYearField.year' + text: 'Example month/year field must include a year' }) ]) }) diff --git a/src/server/plugins/engine/components/NumberField.ts b/src/server/plugins/engine/components/NumberField.ts index aae93c4c9..eea99ffbf 100644 --- a/src/server/plugins/engine/components/NumberField.ts +++ b/src/server/plugins/engine/components/NumberField.ts @@ -137,8 +137,8 @@ export class NumberField extends FormComponent { const { customValidationMessage, customValidationMessages } = this.options const { t } = translator const defaults = { - 'any.required': buildValidationMessages(t).objectRequired, - 'number.base': buildValidationMessages(t).objectMissing, + 'any.required': buildValidationMessages(t).required, + 'number.base': buildValidationMessages(t).number, 'number.precision': buildValidationMessages(t).numberPrecision, 'number.integer': buildValidationMessages(t).numberInteger, 'number.min': buildValidationMessages(t).numberMin, diff --git a/src/server/plugins/engine/components/UkAddressField.test.ts b/src/server/plugins/engine/components/UkAddressField.test.ts index ff641cd44..ac39fe301 100644 --- a/src/server/plugins/engine/components/UkAddressField.test.ts +++ b/src/server/plugins/engine/components/UkAddressField.test.ts @@ -264,16 +264,13 @@ describe('UkAddressField', () => { expect(result.errors).toEqual([ expect.objectContaining({ - text: 'Enter components.addressField.line1' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Enter address line 1' }), expect.objectContaining({ - text: 'Enter components.addressField.town' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Enter town or city' }), expect.objectContaining({ - text: 'Enter components.addressField.postcode' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Enter postcode' }) ]) }) @@ -443,7 +440,6 @@ describe('UkAddressField', () => { expect.objectContaining({ model: getViewModel(address, 'addressLine1', { label: { text: 'Address line 1' }, - // Sub-field title is a key constant; resolved at request time (Task 8/9). attributes: { autocomplete: 'address-line1' } }) }), @@ -451,7 +447,6 @@ describe('UkAddressField', () => { expect.objectContaining({ model: getViewModel(address, 'addressLine2', { label: { text: 'Address line 2 (optional)' }, - // Sub-field title is a key constant; resolved at request time (Task 8/9). attributes: { autocomplete: 'address-line2' }, value: address.addressLine2 }) @@ -460,7 +455,6 @@ describe('UkAddressField', () => { expect.objectContaining({ model: getViewModel(address, 'town', { label: { text: 'Town or city' }, - // Sub-field title is a key constant; resolved at request time (Task 8/9). classes: 'govuk-!-width-two-thirds', attributes: { autocomplete: 'address-level2' }, value: address.town @@ -470,7 +464,6 @@ describe('UkAddressField', () => { expect.objectContaining({ model: getViewModel(address, 'county', { label: { text: 'County (optional)' }, - // Sub-field title is a key constant; resolved at request time (Task 8/9). attributes: { autocomplete: 'address-level1' }, value: address.county }) @@ -479,7 +472,6 @@ describe('UkAddressField', () => { expect.objectContaining({ model: getViewModel(address, 'postcode', { label: { text: 'Postcode' }, - // Sub-field title is a key constant; resolved at request time (Task 8/9). classes: 'govuk-input--width-10', attributes: { autocomplete: 'postal-code' }, value: address.postcode @@ -636,8 +628,7 @@ describe('UkAddressField', () => { }), errors: [ expect.objectContaining({ - text: 'components.addressField.line1 must be 100 characters or less' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Address line 1 must be 100 characters or less' }) ] } @@ -662,8 +653,7 @@ describe('UkAddressField', () => { }), errors: [ expect.objectContaining({ - text: 'components.addressField.line2 must be 100 characters or less' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Address line 2 must be 100 characters or less' }) ] } @@ -688,8 +678,7 @@ describe('UkAddressField', () => { }), errors: [ expect.objectContaining({ - text: 'components.addressField.town must be 100 characters or less' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Town or city must be 100 characters or less' }) ] } @@ -714,8 +703,7 @@ describe('UkAddressField', () => { }), errors: [ expect.objectContaining({ - text: 'components.addressField.county must be 100 characters or less' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'County must be 100 characters or less' }) ] } @@ -740,8 +728,7 @@ describe('UkAddressField', () => { }), errors: [ expect.objectContaining({ - text: 'Enter a valid components.addressField.postcode' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Enter a valid postcode' }) ] } @@ -766,16 +753,13 @@ describe('UkAddressField', () => { }), errors: [ expect.objectContaining({ - text: 'Enter components.addressField.line1' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Enter address line 1' }), expect.objectContaining({ - text: 'Enter components.addressField.town' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Enter town or city' }), expect.objectContaining({ - text: 'Enter a valid components.addressField.postcode' - // Sub-field title is a key constant; resolved at request time (Task 8/9). + text: 'Enter a valid postcode' }) ] } diff --git a/src/server/plugins/engine/components/defaultTranslator.test.ts b/src/server/plugins/engine/components/defaultTranslator.test.ts index 74fd3d081..2bd929811 100644 --- a/src/server/plugins/engine/components/defaultTranslator.test.ts +++ b/src/server/plugins/engine/components/defaultTranslator.test.ts @@ -159,10 +159,7 @@ describe.each(cases)( it('uses English', () => { const value = component.getFormValueFromState(state) - const { errors = [] } = collection.validate( - payload, - model.createTranslator() - ) + const { errors = [] } = collection.validate(payload) const { fieldset, label } = field.getViewModel({ payload: collection.getFormDataFromState(state) }) as { diff --git a/src/server/plugins/engine/models/SummaryViewModel.ts b/src/server/plugins/engine/models/SummaryViewModel.ts index 95935f6bf..f67fc135b 100644 --- a/src/server/plugins/engine/models/SummaryViewModel.ts +++ b/src/server/plugins/engine/models/SummaryViewModel.ts @@ -4,7 +4,6 @@ import { type Section } from '@defra/forms-model' -import { EN_GB } from '~/src/server/constants.js' import { PaymentField } from '~/src/server/plugins/engine/components/PaymentField.js' import { type PaymentState } from '~/src/server/plugins/engine/components/PaymentField.types.js' import { @@ -97,7 +96,9 @@ export class SummaryViewModel { .validate(this.context.relevantState, { ...opts, stripUnknown: true }) // Format errors - this.errors = result.error?.details.map((item) => getError(item, EN_GB)) + this.errors = result.error?.details.map((item) => + getError(item, translator.language) + ) this.details = this.summaryDetails(request, sections, translator) // Format check answers diff --git a/src/server/plugins/engine/pageControllers/validationOptions.ts b/src/server/plugins/engine/pageControllers/validationOptions.ts index baacd2605..c9a551fd5 100644 --- a/src/server/plugins/engine/pageControllers/validationOptions.ts +++ b/src/server/plugins/engine/pageControllers/validationOptions.ts @@ -62,14 +62,6 @@ export const messages: LanguageMessagesExt = { 'array.max': messageTemplate.arrayMax, 'array.length': messageTemplate.arrayLength, - 'features.min': messageTemplate.featuresMin, - 'features.max': messageTemplate.featuresMax, - 'features.length': messageTemplate.featuresLength, - - 'files.min': messageTemplate.filesMin, - 'files.max': messageTemplate.filesMax, - 'filees.length': messageTemplate.filesLength, - 'object.invalidjson': messageTemplate.format, 'phoneNumber.invalid': messageTemplate.format @@ -109,12 +101,6 @@ export function buildLanguageMessages( 'array.min': vm.arrayMin, 'array.max': vm.arrayMax, 'array.length': vm.arrayLength, - 'features.min': vm.featuresMin, - 'features.max': vm.featuresMax, - 'features.length': vm.featuresLength, - 'files.min': vm.filesMin, - 'files.max': vm.filesMax, - 'files.length': vm.filesLength, 'object.invalidjson': vm.format, 'phoneNumber.invalid': vm.format } as unknown as LanguageMessages diff --git a/test/form/components-translated.test.js b/test/form/components-translated.test.js new file mode 100644 index 000000000..e021f73c5 --- /dev/null +++ b/test/form/components-translated.test.js @@ -0,0 +1,142 @@ +import { resolve } from 'node:path' + +import { within } from '@testing-library/dom' + +import { FORM_PREFIX } from '~/src/server/constants.js' +import { createServer } from '~/src/server/index.js' +import { FormModel } from '~/src/server/plugins/engine/models/FormModel.js' +import { getFormMetadata } from '~/src/server/plugins/engine/services/formsService.js' +import { + getUploadStatus, + initiateUpload +} from '~/src/server/plugins/engine/services/uploadService.js' +import { UploadStatus } from '~/src/server/plugins/engine/types.js' +import * as fixtures from '~/test/fixtures/index.js' +import definition from '~/test/form/definitions/components-translated.js' +import { renderResponse } from '~/test/helpers/component-helpers.js' +import { getCookieHeader } from '~/test/utils/get-cookie.js' + +const basePath = `${FORM_PREFIX}/components-translated` + +jest.mock('~/src/server/plugins/engine/services/formsService.js') +jest.mock('~/src/server/plugins/engine/services/uploadService.js') + +describe('Welsh file upload, guidance and payment', () => { + /** @type {Server} */ + let server + + /** @type {ReturnType} */ + let headers + + beforeAll(async () => { + server = await createServer({ + formFileName: 'components-translated.js', + formFilePath: resolve(import.meta.dirname, 'definitions'), + enforceCsrf: false + }) + + await server.initialize() + }) + + beforeEach(async () => { + jest.mocked(getFormMetadata).mockResolvedValue(fixtures.form.metadata) + jest.mocked(initiateUpload).mockResolvedValue({ + uploadId: 'upload-id', + uploadUrl: 'http://localhost/upload', + statusUrl: 'http://localhost/status' + }) + + const response = await server.inject({ + url: `${basePath}/upload?language=cy` + }) + + headers = getCookieHeader(response, 'session') + + jest.mocked(getUploadStatus).mockResolvedValue({ + uploadStatus: UploadStatus.initiated, + metadata: { retrievalKey: 'enrique.chase@defra.gov.uk' }, + form: {} + }) + }) + + afterAll(async () => { + await server.stop() + }) + + it('shows the file upload page in Welsh', async () => { + const { container } = await renderResponse(server, { + url: `${basePath}/upload`, + headers + }) + + expect( + container.getByRole('heading', { + name: 'Welsh Upload your plan', + level: 1 + }) + ).toBeInTheDocument() + expect( + container.getByText('Welsh Read the guidance first') + ).toBeInTheDocument() + expect( + container.getByLabelText('Welsh Upload your plan') + ).toBeInTheDocument() + }) + + it('shows the file upload error in Welsh', async () => { + const { container } = await renderResponse(server, { + url: `${basePath}/upload`, + method: 'POST', + headers, + payload: {} + }) + + const $errorSummary = container.getByRole('alert') + + expect( + within($errorSummary).getByRole('heading', { + name: 'Mae problem', + level: 2 + }) + ).toBeInTheDocument() + expect( + within($errorSummary).getByRole('link', { + name: 'Dewiswch welsh Upload your plan' + }) + ).toHaveAttribute('href', '#plan') + }) + + it('shows the payment page in Welsh', async () => { + const { container } = await renderResponse(server, { + url: `${basePath}/payment`, + headers + }) + + expect( + container.getByRole('heading', { name: 'Welsh Pay the fee', level: 2 }) + ).toBeInTheDocument() + expect(container.getByText('Welsh Licence fee')).toBeInTheDocument() + expect( + container.getByRole('button', { name: 'Ychwanegu manylion talu' }) + ).toBeInTheDocument() + }) + + it('shows the payment error in Welsh', async () => { + const model = new FormModel(definition, { basePath: 'test' }) + const [field] = model.pages[1].collection.fields + const request = { + server: { + plugins: { 'forms-engine-plugin': { getLanguage: () => 'cy' } } + } + } + + await expect( + // @ts-expect-error - partial request and context + field.onSubmit(request, {}, { state: {} }) + ).rejects.toMatchObject({ userMessage: 'Cwblhewch y taliad i barhau' }) + }) +}) + +/** + * @import { Server } from '@hapi/hapi' + */ diff --git a/test/form/definitions/components-translated.js b/test/form/definitions/components-translated.js new file mode 100644 index 000000000..429f9310e --- /dev/null +++ b/test/form/definitions/components-translated.js @@ -0,0 +1,85 @@ +import { + ComponentType, + ControllerPath, + ControllerType, + Engine +} from '@defra/forms-model' + +export default /** @satisfies {FormDefinition} */ ({ + name: 'Components translated', + engine: Engine.V2, + schema: 2, + startPage: '/upload', + pages: /** @type {const} */ ([ + { + id: '1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e01', + path: '/upload', + title: 'Upload your plan', + controller: ControllerType.FileUpload, + components: [ + { + id: '1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e02', + name: 'guidance', + title: 'Guidance', + type: ComponentType.Markdown, + content: 'Read the guidance first', + options: {} + }, + { + id: '1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e03', + name: 'plan', + title: 'Upload your plan', + type: ComponentType.FileUploadField, + options: {}, + schema: {} + } + ], + next: [{ path: '/payment' }] + }, + { + id: '1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e04', + path: '/payment', + title: 'Pay the fee', + components: [ + { + id: '1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e05', + name: 'payment', + title: 'Pay the licence fee', + type: ComponentType.PaymentField, + options: { amount: 10, description: 'Licence fee' } + } + ], + next: [{ path: ControllerPath.Summary }] + }, + { + id: '1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e06', + path: ControllerPath.Summary, + controller: ControllerType.Summary, + title: 'Check your answers' + } + ]), + sections: [], + conditions: [], + lists: [], + metadata: { + translations: { + cy: { + 'pages.1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e01.title': + 'Welsh Upload your plan', + 'components.1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e02.content': + 'Welsh Read the guidance first', + 'components.1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e03.title': + 'Welsh Upload your plan', + 'pages.1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e04.title': 'Welsh Pay the fee', + 'components.1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e05.title': + 'Welsh Pay the licence fee', + 'components.1b0c6a0e-6c5d-4a8e-9f1e-0d7a1c2b3e05.paymentDescription': + 'Welsh Licence fee' + } + } + } +}) + +/** + * @import { FormDefinition } from '@defra/forms-model' + */ diff --git a/test/form/definitions/fields-required-translated.js b/test/form/definitions/fields-required-translated.js index 25805b2dd..0ba17bb3b 100644 --- a/test/form/definitions/fields-required-translated.js +++ b/test/form/definitions/fields-required-translated.js @@ -21,6 +21,7 @@ export default /** @satisfies {FormDefinition} */ ({ hint: 'Help text', options: {}, schema: { + min: 3, max: 30 } }, diff --git a/test/form/definitions/file-upload-limits.js b/test/form/definitions/file-upload-limits.js new file mode 100644 index 000000000..3209f1d03 --- /dev/null +++ b/test/form/definitions/file-upload-limits.js @@ -0,0 +1,72 @@ +import { + ComponentType, + ControllerPath, + ControllerType, + Engine +} from '@defra/forms-model' + +export default /** @satisfies {FormDefinition} */ ({ + name: 'File upload limits', + engine: Engine.V2, + schema: 2, + startPage: '/min-max', + pages: /** @type {const} */ ([ + { + id: '3d2e8c2a-8e7f-4c0a-9b3b-2f9c3d4e5f01', + path: '/min-max', + title: 'Upload between 2 and 3 files', + controller: ControllerType.FileUpload, + components: [ + { + id: '3d2e8c2a-8e7f-4c0a-9b3b-2f9c3d4e5f02', + name: 'minMax', + title: 'Upload between 2 and 3 files', + type: ComponentType.FileUploadField, + options: {}, + schema: { min: 2, max: 3 } + } + ], + next: [{ path: '/exact' }] + }, + { + id: '3d2e8c2a-8e7f-4c0a-9b3b-2f9c3d4e5f03', + path: '/exact', + title: 'Upload exactly 2 files', + controller: ControllerType.FileUpload, + components: [ + { + id: '3d2e8c2a-8e7f-4c0a-9b3b-2f9c3d4e5f04', + name: 'exact', + title: 'Upload exactly 2 files', + type: ComponentType.FileUploadField, + options: {}, + schema: { length: 2 } + } + ], + next: [{ path: ControllerPath.Summary }] + }, + { + id: '3d2e8c2a-8e7f-4c0a-9b3b-2f9c3d4e5f05', + path: ControllerPath.Summary, + controller: ControllerType.Summary, + title: 'Check your answers' + } + ]), + sections: [], + conditions: [], + lists: [], + metadata: { + translations: { + cy: { + 'components.3d2e8c2a-8e7f-4c0a-9b3b-2f9c3d4e5f02.title': + 'Welsh Upload between 2 and 3 files', + 'components.3d2e8c2a-8e7f-4c0a-9b3b-2f9c3d4e5f04.title': + 'Welsh Upload exactly 2 files' + } + } + } +}) + +/** + * @import { FormDefinition } from '@defra/forms-model' + */ diff --git a/test/form/definitions/repeat-translated.js b/test/form/definitions/repeat-translated.js new file mode 100644 index 000000000..1e7e78328 --- /dev/null +++ b/test/form/definitions/repeat-translated.js @@ -0,0 +1,56 @@ +import { + ComponentType, + ControllerPath, + ControllerType, + Engine +} from '@defra/forms-model' + +export default /** @satisfies {FormDefinition} */ ({ + name: 'Repeat translated', + engine: Engine.V2, + schema: 2, + startPage: '/people', + pages: /** @type {const} */ ([ + { + id: '5a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c01', + path: '/people', + title: 'People', + controller: ControllerType.Repeat, + repeat: { + options: { name: 'people', title: 'Person' }, + schema: { min: 2, max: 3 } + }, + components: [ + { + id: '5a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c02', + name: 'person', + title: 'Person name', + type: ComponentType.TextField, + options: {}, + schema: {} + } + ], + next: [{ path: ControllerPath.Summary }] + }, + { + id: '5a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c03', + path: ControllerPath.Summary, + controller: ControllerType.Summary, + title: 'Check your answers' + } + ]), + sections: [], + conditions: [], + lists: [], + metadata: { + translations: { + cy: { + 'components.5a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c02.title': 'Enw person' + } + } + } +}) + +/** + * @import { FormDefinition } from '@defra/forms-model' + */ diff --git a/test/form/fields-required-translated.test.js b/test/form/fields-required-translated.test.js index f32b7efc4..d4a09ace1 100644 --- a/test/form/fields-required-translated.test.js +++ b/test/form/fields-required-translated.test.js @@ -31,6 +31,7 @@ describe('Form fields (required)', () => { payload: { empty: { textField: '' }, invalid: { textField: 'This text is too long for the field' }, + invalid2: { textField: 'ab' }, valid: { textField: 'Example text field' } } }, @@ -50,6 +51,7 @@ describe('Form fields (required)', () => { payload: { empty: { numberField: '' }, invalid: { numberField: '123456' }, + invalid2: { numberField: 'abc' }, valid: { numberField: '1234' } } }, @@ -452,7 +454,7 @@ describe('Form fields (required)', () => { expect($errors).toHaveLength(26) expect($errors[0].textContent).toBe('Nodwch welsh textfield error desc') expect($errors[1].textContent).toBe('Nodwch welsh Multiline text field') - expect($errors[2].textContent).toBe('Nodwch Welsh Number field') + expect($errors[2].textContent).toBe('Nodwch welsh Number field') expect($errors[3].textContent).toBe( 'Rhaid i Welsh Date parts field gynnwys diwrnod' ) @@ -471,7 +473,7 @@ describe('Form fields (required)', () => { expect($errors[10].textContent).toBe('Nodwch cod post') expect($errors[11].textContent).toBe('Dewiswch welsh Radios field') expect($errors[12].textContent).toBe('Dewiswch welsh Select field') - expect($errors[13].textContent).toBe('Nodwch Welsh Autocomplete field') + expect($errors[13].textContent).toBe('Nodwch welsh Autocomplete field') expect($errors[14].textContent).toBe( 'Dewiswch welsh Checkboxes field 1' ) @@ -552,7 +554,7 @@ describe('Form fields (required)', () => { expect($errors[8].textContent).toBe('Nodwch cod post dilys') expect($errors[9].textContent).toBe('Dewiswch welsh Radios field') expect($errors[10].textContent).toBe('Dewiswch welsh Select field') - expect($errors[11].textContent).toBe('Nodwch Welsh Autocomplete field') + expect($errors[11].textContent).toBe('Nodwch welsh Autocomplete field') expect($errors[12].textContent).toBe( 'Dewiswch welsh Checkboxes field 1' ) @@ -625,6 +627,12 @@ describe('Form fields (required)', () => { const $errors = $errorSummary.querySelectorAll('a') expect($errors).toHaveLength(24) + expect($errors[0].textContent).toBe( + 'Rhaid i Welsh textfield error desc fod yn 3 o nodau neu fwy' + ) + expect($errors[2].textContent).toBe( + 'Rhaid i Welsh Number field fod yn rhif' + ) expect($errors[6].textContent).toBe( 'Mae Welsh Email address field yn cynnwys nodau annilys, er enghraifft, dashes hirion' ) diff --git a/test/form/file-upload.test.js b/test/form/file-upload.test.js index 26ca0e678..f175f1ae3 100644 --- a/test/form/file-upload.test.js +++ b/test/form/file-upload.test.js @@ -1,3 +1,4 @@ +import { randomUUID } from 'node:crypto' import { resolve } from 'node:path' import { within } from '@testing-library/dom' @@ -312,6 +313,164 @@ describe('File upload POST tests', () => { }) }) +describe('File upload limits', () => { + const limitsBasePath = `${FORM_PREFIX}/file-upload-limits` + + /** @type {Server} */ + let server + + beforeAll(async () => { + server = await createServer({ + formFileName: 'file-upload-limits.js', + formFilePath: resolve(import.meta.dirname, 'definitions'), + enforceCsrf: false + }) + + await server.initialize() + }) + + beforeEach(() => { + jest.mocked(getFormMetadata).mockResolvedValue(fixtures.form.metadata) + jest.mocked(initiateUpload).mockImplementation(() => { + const uploadId = randomUUID() + + return Promise.resolve({ + uploadId, + uploadUrl: `http://localhost:7337/upload-and-scan/${uploadId}`, + statusUrl: `http://localhost:7337/status/${uploadId}` + }) + }) + }) + + afterAll(async () => { + await server.stop() + }) + + /** + * Upload files in one go through the stubbed upload service, as when a user + * selects several files, then post the page + * @param {ReturnType} headers + * @param {string} path + * @param {number} count + */ + async function uploadAndPost(headers, path, count) { + const file = Array.from({ length: count }, (_, i) => ({ + fileId: randomUUID(), + filename: `file-${i + 1}.pdf`, + contentLength: 1024, + fileStatus: FileStatus.complete + })) + + // @ts-expect-error - the upload service sends an array for several files + jest.mocked(getUploadStatus).mockResolvedValueOnce({ + uploadStatus: UploadStatus.ready, + metadata, + form: { file }, + numberOfRejectedFiles: 0 + }) + + await server.inject({ url: `${limitsBasePath}${path}`, headers }) + + return renderResponse(server, { + url: `${limitsBasePath}${path}`, + method: 'POST', + headers, + payload: {} + }) + } + + /** + * @param {string} path + * @param {number} count + * @param {string} language + */ + async function getErrorLink(path, count, language) { + jest.mocked(getUploadStatus).mockResolvedValue({ + uploadStatus: UploadStatus.initiated, + metadata, + form: {} + }) + + const response = await server.inject({ + url: `${limitsBasePath}/min-max?language=${language}` + }) + + const headers = getCookieHeader(response, 'session') + + // The exact page shows only after the page before it is complete + if (path === '/exact') { + await uploadAndPost(headers, '/min-max', 2) + await server.inject({ url: `${limitsBasePath}/exact`, headers }) + } + + const { container } = await uploadAndPost(headers, path, count) + + const $errorSummary = container + .getAllByRole('alert') + .find(($alert) => within($alert).queryAllByRole('listitem').length) + + return $errorSummary + ? within($errorSummary).getByRole('link').textContent.trim() + : undefined + } + + it.each([ + { + path: '/min-max', + count: 1, + language: 'en-GB', + error: 'You must upload 2 files or more' + }, + { + path: '/min-max', + count: 4, + language: 'en-GB', + error: 'You can only upload 3 files or less' + }, + { + path: '/exact', + count: 1, + language: 'en-GB', + error: 'You must upload exactly 2 files' + }, + { + path: '/exact', + count: 3, + language: 'en-GB', + error: 'You must upload exactly 2 files' + }, + { + path: '/min-max', + count: 1, + language: 'cy', + error: 'Rhaid i chi uwchlwytho 2 o ffeiliau neu fwy' + }, + { + path: '/min-max', + count: 4, + language: 'cy', + error: 'Dim ond 3 o ffeiliau neu lai y gallwch eu huwchlwytho' + }, + { + path: '/exact', + count: 1, + language: 'cy', + error: "Rhaid i chi uwchlwytho'n union 2 o ffeiliau" + }, + { + path: '/exact', + count: 3, + language: 'cy', + error: "Rhaid i chi uwchlwytho'n union 2 o ffeiliau" + } + ])( + '$path with $count files in $language shows "$error"', + async ({ path, count, language, error }) => { + expect(await getErrorLink(path, count, language)).toBe(error) + } + ) +}) + /** * @import { Server } from '@hapi/hapi' * @import { UploadInitiateResponse, UploadStatusResponse } from '~/src/server/plugins/engine/types.js' diff --git a/test/form/repeat.test.js b/test/form/repeat.test.js index 626ebff23..c996416c5 100644 --- a/test/form/repeat.test.js +++ b/test/form/repeat.test.js @@ -655,6 +655,57 @@ describe('Repeat POST tests', () => { }) }) +describe('Repeat in Welsh', () => { + const translatedBasePath = `${FORM_PREFIX}/repeat-translated` + + /** @type {Server} */ + let server + + beforeAll(async () => { + server = await createServer({ + formFileName: 'repeat-translated.js', + formFilePath: resolve(import.meta.dirname, 'definitions'), + enforceCsrf: false + }) + + await server.initialize() + }) + + beforeEach(() => { + jest.mocked(getFormMetadata).mockResolvedValue(fixtures.form.metadata) + }) + + afterAll(async () => { + await server.stop() + }) + + test('shows the repeater error in Welsh', async () => { + const response = await server.inject({ + url: `${translatedBasePath}/people?language=cy` + }) + + const headers = getCookieHeader(response, 'session') + + await server.inject({ + url: `${translatedBasePath}/people/${crypto.randomUUID()}`, + method: 'POST', + headers, + payload: { person: 'Ann' } + }) + + const { container } = await renderResponse(server, { + url: `${translatedBasePath}/people/summary`, + method: 'POST', + headers, + payload: { action: FormAction.Continue } + }) + + expect(container.getByRole('alert')).toHaveTextContent( + 'Rhaid i chi ychwanegu o leiaf ddau gateb' + ) + }) +}) + /** * @import { Server } from '@hapi/hapi' * @import { PageRepeat } from '@defra/forms-model'