Skip to content

Commit

Permalink
add a unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
Dosant committed Sep 14, 2022
1 parent d3fb0af commit 5f85cba
Showing 1 changed file with 69 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import { emptyField } from '../../helpers/field_validators';
import { FieldHook, FieldValidateResponse, VALIDATION_TYPES, FieldConfig } from '..';

describe('useField() hook', () => {
let fieldHook: FieldHook;

beforeAll(() => {
jest.useFakeTimers();
});
Expand All @@ -26,22 +24,23 @@ describe('useField() hook', () => {
jest.useRealTimers();
});

const TestField = ({ field }: { field: FieldHook }) => {
fieldHook = field;
return null;
};

const getTestForm = (config?: FieldConfig) => () => {
const { form } = useForm();

return (
<Form form={form}>
<UseField path="test-path" component={TestField} config={config} />
</Form>
);
};

describe('field.validate()', () => {
let fieldHook: FieldHook;
const TestField = ({ field }: { field: FieldHook }) => {
fieldHook = field;
return null;
};

const getTestForm = (config?: FieldConfig) => () => {
const { form } = useForm();

return (
<Form form={form}>
<UseField path="test-path" component={TestField} config={config} />
</Form>
);
};

const EMPTY_VALUE = ' ';

test('it should not invalidate a field with arrayItem validation when isBlocking is false', async () => {
Expand Down Expand Up @@ -149,4 +148,57 @@ describe('useField() hook', () => {
expect(validatorFn).toBeCalledTimes(0);
});
});

describe('fieldsToValidateOnChange', () => {
let fieldHook1: FieldHook;
let fieldHook2: FieldHook;
const TestField1 = ({ field }: { field: FieldHook }) => {
fieldHook1 = field;
return null;
};

const TestField2 = ({ field }: { field: FieldHook }) => {
fieldHook2 = field;
return null;
};

const getTestForm =
(configField1?: FieldConfig, configField2?: FieldConfig) =>
({ showField1, showField2 }: { showField1: boolean; showField2: boolean }) => {
const { form } = useForm();

return (
<Form form={form}>
{showField1 && <UseField path="field1" component={TestField1} config={configField1} />}
{showField2 && <UseField path="field2" component={TestField2} config={configField2} />}
</Form>
);
};

test('validates dependent fields on unmount', async () => {
const field2ValidatorFn = jest.fn();
const TestForm = getTestForm(
{
fieldsToValidateOnChange: ['field1', 'field2'],
},
{
validations: [
{
validator: field2ValidatorFn,
},
],
}
);

const wrapper = registerTestBed(TestForm, {
memoryRouter: { wrapComponent: false },
})({ showField1: true, showField2: true });
expect(field2ValidatorFn).toBeCalledTimes(0);

await act(async () => {
wrapper.setProps({ showField1: false });
});
expect(field2ValidatorFn).toBeCalledTimes(1);
});
});
});

0 comments on commit 5f85cba

Please sign in to comment.