Skip to content

Commit 0bf0354

Browse files
committed
fix required() tests and add additional coverage
1 parent b1557b9 commit 0bf0354

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

lib/interviewer/utils/__tests__/field-validations.test.ts

+13-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,19 @@ describe('Validations', () => {
9191
});
9292
describe('required()', () => {
9393
const errorMessage = 'You must answer this question before continuing';
94-
const subject = required();
94+
const subject = required(true);
95+
96+
it('handles initialisation with boolean or string to determine message', () => {
97+
const withBooleanMessage = required(true);
98+
const withStringMessage = required('Custom message');
99+
100+
expect(withBooleanMessage('')).toBe(
101+
'You must answer this question before continuing',
102+
);
103+
expect(withStringMessage('')).toBe('Custom message');
104+
expect(withStringMessage('hello')).toBe(undefined);
105+
expect(withBooleanMessage('hello')).toBe(undefined);
106+
});
95107

96108
it('passes for a string', () => {
97109
expect(subject('hello world')).toBe(undefined);

lib/interviewer/utils/field-validation.ts

+10-4
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,19 @@ const coerceArray = (value: FieldValue) => {
4343
// to be able to specify a string for the message in some cases. A better
4444
// design would probably be to have a separate validation function for
4545
// required that takes a message.
46-
export const required = (message?: string | boolean) => (value: FieldValue) => {
46+
export const required = (message: string | true) => (value: FieldValue) => {
4747
const isEmptyString = isString(value) && value.length === 0;
4848

4949
if (isNil(value) || isEmptyString) {
50-
return typeof message === 'boolean' && message === true
51-
? 'You must answer this question before continuing'
52-
: message;
50+
// If initialised with a string, assume required is true
51+
// and return the string as the message
52+
if (typeof message === 'string') {
53+
return message;
54+
}
55+
56+
// Otherwise, return the default message. Note: 'false' is not handled because
57+
// we have never used it.
58+
return 'You must answer this question before continuing';
5359
}
5460

5561
return undefined;

0 commit comments

Comments
 (0)