diff --git a/src/app/components/PasswordField/__tests__/index.test.tsx b/src/app/components/PasswordField/__tests__/index.test.tsx new file mode 100644 index 0000000000..c179dfe77c --- /dev/null +++ b/src/app/components/PasswordField/__tests__/index.test.tsx @@ -0,0 +1,94 @@ +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { Form, FormField, TextInput } from 'grommet' +import * as React from 'react' +import { PasswordField } from '..' + +interface FormValue { + name: string + privateKey: string +} + +describe('', () => { + it('with `name` and `validate`: validation error blocks submitting', async () => { + function Example(props: { onSubmit: (value: FormValue) => void }) { + return ( + + onSubmit={({ value }) => { + expect(value.privateKey.length).toBeGreaterThanOrEqual(5) + props.onSubmit(value) + }} + > + + + + + inputElementId="privateKey" + name="privateKey" + label="privateKey" + autoComplete="current-password" + validate={(privateKey, form) => { + return privateKey.length < 5 ? 'invalid' : undefined + }} + showTip="show" + hideTip="hide" + /> + + + ) + } + const onSubmit = jest.fn() + render() + + await userEvent.type(screen.getByLabelText('privateKey'), 'a {Enter}') + expect(await screen.findByText('invalid')).toBeInTheDocument() + expect(onSubmit).not.toHaveBeenCalled() + + await userEvent.type(screen.getByLabelText('privateKey'), 'privateKey{Enter}') + expect(screen.queryByText('invalid')).not.toBeInTheDocument() + expect(onSubmit).toHaveBeenLastCalledWith({ name: 'name', privateKey: 'a privateKey' }) + }) + + it('with `value`, `onChange`, and `error`: validation error does NOT block submitting', async () => { + function Example(props: { onSubmit: (value: FormValue) => void }) { + const [privateKey, setPrivateKey] = React.useState('') + const [name, setName] = React.useState('name') + return ( +
{ + // Error doesn't block onSubmit + // expect(privateKey.length).toBeGreaterThanOrEqual(5) + props.onSubmit({ name, privateKey }) + }} + > + + setName(event.target.value)} /> + + setPrivateKey(event.target.value)} + error={privateKey.length < 5 ? 'invalid' : undefined} + showTip="show" + hideTip="hide" + /> + + + ) + } + const onSubmit = jest.fn() + render() + + await userEvent.type(screen.getByLabelText('privateKey'), 'a {Enter}') + expect(await screen.findByText('invalid')).toBeInTheDocument() + // Error doesn't block onSubmit + expect(onSubmit).toHaveBeenLastCalledWith({ name: 'name', privateKey: 'a ' }) + + await userEvent.type(screen.getByLabelText('privateKey'), 'privateKey{Enter}') + expect(screen.queryByText('invalid')).not.toBeInTheDocument() + expect(onSubmit).toHaveBeenLastCalledWith({ name: 'name', privateKey: 'a privateKey' }) + }) +})