Skip to content

Commit 8daa83d

Browse files
authored
Checkbox - validate to return validity (#3672)
* Fix validation logic in Checkbox component to return error state * Added tests to cover validate return value * Better readability to validate function
1 parent 06f0f39 commit 8daa83d

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/components/checkbox/__tests__/index.spec.tsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,19 @@ describe('Checkbox renderer test', () => {
158158

159159
expect(onChangeValidity).toHaveBeenCalledWith(false);
160160
});
161+
162+
it.each([false, true])('should return validity from validate function - initial %s', async (initialValue) => {
163+
const props: CheckboxProps = {required: true, onChangeValidity, value: initialValue};
164+
const renderTree = render(<TestCase {...props}/>);
165+
const driver = CheckboxDriver({renderTree, testID});
166+
167+
expect(checkboxRef.current?.validate()).toBe(initialValue);
168+
169+
await driver.press();
170+
171+
expect(checkboxRef.current?.validate()).toBe(!initialValue);
172+
173+
});
161174
});
162175

163176
describe('isValid', () => {

src/components/checkbox/index.tsx

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -306,9 +306,10 @@ class Checkbox extends Component<CheckboxProps, CheckboxState> {
306306

307307
validate = () => {
308308
const {value, required} = this.props;
309-
const error = required && !value;
310-
this.validationState = true;
311-
this.setState({showError: error, isValid: !error});
309+
const isValid = !(required && !value);
310+
this.validationState = true;
311+
this.setState({showError: !isValid, isValid});
312+
return isValid;
312313
};
313314

314315
isValid = () => {

0 commit comments

Comments
 (0)