Ale*_*min 6 javascript unit-testing reactjs react-testing-library
我用来react-hook-form
控制我的表单输入(ChakraUI 输入)并禁用“提交”按钮以防输入无效
由于我FormProvider
在父组件中使用了多页表单,因此根据当前页面更改验证架构
const currentValidationSchema = validationSchema[activeStep];
const methods = useForm({
mode: 'all',
defaultValues: DEFAULT_VALUES,
resolver: yupResolver(currentValidationSchema),
});
Run Code Online (Sandbox Code Playgroud)
<FormProvider {...methods}>
<Box >{renderCurrentStep(activeStep)}</Box>
</FormProvider>
Run Code Online (Sandbox Code Playgroud)
useFormContext
并在子组件中使用它
const {
control,
watch,
getValues,
clearErrors,
setError,
setValue,
formState: { errors, isValid },
} = useFormContext<IOrderProductFormData>();
Run Code Online (Sandbox Code Playgroud)
<Controller
control={control}
name="phoneNumber"
render={({ field: { onChange, value } }) => {
return (
<InputMask
mask="999 99 999"
onChange={onChange}
maskChar=" "
value={value}
>
{(inputProps: any) => (
<InputGroup variant="phone">
<InputLeftAddon>+1</InputLeftAddon>
<Input
type="tel"
ref={inputRef}
aria-label="phone-number"
data-testid="phone-number"
{...inputProps}
/>
</InputGroup>
)}
</InputMask>
);
}}
/>
Run Code Online (Sandbox Code Playgroud)
如果表单未通过验证但当前架构通过,则按钮将被禁用
<ArrowButton onClick={handleSendOtp} disabled={!isValid} />
Run Code Online (Sandbox Code Playgroud)
代码按预期工作,但我正在努力编写单元测试来验证按钮确实在必要时被禁用。
describe('<PhoneNumber />', () => {
beforeEach(async () => {
await act(async () => {
render(
<WrapperForm>
<WrapperRouter>
<PhoneNumber {...props} />
</WrapperRouter>
</WrapperForm>
);
});
});
describe('with valid input', () => {
it('should show enabled button', async () => {
const nextPageButton = screen.getByRole('button', { name: 'chevron-right' });
fireEvent.input(screen.getByTestId('phone-number'), {
target: {
value: '22222222',
},
});
expect(nextPageButton).not.toBeDisabled();
});
});
describe('with invalid input', () => {
it('should show disabled button', async () => {
const nextPageButton = screen.getByRole('button', { name: 'chevron-right' });
fireEvent.input(screen.getByTestId('phone-number'), {
target: {
value: '0',
},
});
expect(nextPageButton).toBeDisabled();
});
});
});
Run Code Online (Sandbox Code Playgroud)
第一步通过了,它应该具有有效值。然而,第二个失败并显示以下消息
Run Code Online (Sandbox Code Playgroud)expect(element).toBeDisabled() Received element is not disabled: <button aria-label="chevron-right" class="chakra-button css-5c2176" name="chevron-right" type="button" />
由于某种原因,按钮上没有disabled
属性,尽管它在 UI 上工作得很好。我希望得到一些帮助