Skip to content

Commit

Permalink
fix(Forms): ensure setFieldStatus by useValidation does not throw w…
Browse files Browse the repository at this point in the history
…hen used without id
  • Loading branch information
tujoworker committed Feb 3, 2025
1 parent 4f19474 commit c84661d
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,11 @@ describe('useValidation', () => {
})

describe('setFieldStatus', () => {
it('should not throw when no id is given', () => {
const { result } = renderHook(useValidation)
result.current.setFieldStatus('/path', { error: null })
})

describe('with an identifier', () => {
it('should set and remove a field error', async () => {
const onSubmit = jest.fn()
Expand Down Expand Up @@ -469,6 +474,43 @@ describe('useValidation', () => {
expect(info).toHaveTextContent('Show me again')
})
})

it('should handle the setFormError method outside of the form context', async () => {
const myId = () => null
const onSubmit = jest.fn()

const MockComponent = () => {
const { setFieldStatus } = useValidation(myId)

return (
<Form.Handler id={myId} onSubmit={onSubmit}>
<Field.String
label="My field"
path="/myField"
onChange={(value) => {
if (value === 'error') {
setFieldStatus('/myField', {
error: new Error('Error message'),
})
}
}}
/>
</Form.Handler>
)
}

render(<MockComponent />)

await userEvent.type(document.querySelector('input'), 'error')

fireEvent.submit(document.querySelector('form'))

expect(onSubmit).toHaveBeenCalledTimes(0)

expect(
document.querySelector('.dnb-form-status')
).toBeInTheDocument()
})
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ function useConnections(id: SharedStateId = undefined) {
const connections =
attachments?.fieldConnectionsRef || (!id && fieldConnectionsRef)

return connections.current
return connections?.current
}, [fieldConnectionsRef, get, id])

return useMemo(() => ({ getFieldConnections }), [getFieldConnections])
Expand Down

0 comments on commit c84661d

Please sign in to comment.