我测试了我的 SimpleForm,但即使在成功写入输入后,我的 SaveButton 仍然被禁用(包含 className 'Mui-disabled')。
npm 包在这里很有用:
工具栏:
const SaveCancelDeleteToolbar = (props: SaveCancelDeleteToolbarProps) => {
const { closeDrawer, handleCancel } = props
const translate = useTranslate()
const {
formState: { isValid },
} = useFormContext()
return (
<Toolbar>
<SaveButton disabled={!isValid} onClick={closeDrawer} />
<Button onClick={handleCancel}>{translate('ra.action.cancel')}</Button>
</Toolbar>
)
}
形式:
<SimpleForm mode="all" reValidateMode="onChange" toolbar={toolbar}>
<TextInput
data-testid="form.value"
label="resources.values.fields.value"
source="value"
validate={[required(), maxLength(50), noEmptySpace]}
/>
</SimpleForm>
为了防止测试环境中的react-hook-form崩溃,我必须使用包装器来添加
const formMethods = useForm()
测试文件:
it('should be able to create element', async () => {
// ValueList contains somewhere the SimpleForm.
const { user, ...utils } = setup(
<FormContextWrapper resource="vat-rates">
<ValueList deleted={false} />
</FormContextWrapper>
)
/* Some code that open my SimpleForm **/
// Check that SaveButton is disabled when pristine
const saveButton = await screen.findByText('ra.action.save')
expect(saveButton.outerHTML.includes('Mui-disabled')).toBe(true)
const divValue = await screen.findByTestId(
'form.value'
)
const inputValue = divValue.children[1].children[0]
fireEvent.focus(inputValue )
await user.type(inputValue , '1')
fireEvent.blur(inputValue )
// This expect is successful, my input has been set to '1'.
expect(inputValue.value).toBe('1')
await waitFor(() => {
const saveButton2 = screen.getByText('ra.action.save')
// This expect fails. saveButton2 exist.
// Its outerHTML is the following. In react-admin I saw that in DOM, disabled is always "" so I check with 'Mui-disabled' presence.
// `<button class="LotsOfClasses Mui-disabled" tabindex="-1" type="submit" disabled="" aria-label="ra.action.save">ra.action.save</button>`
expect(saveButton2.outerHTML.includes('Mui-disabled')).toBe(false)
})
})
由于未知原因,SaveCancelDeleteToolbar 组件未在测试环境中重新渲染。因此 isValid 保持 false 并且 SaveButton 仍然具有“Mui-disabled”className。
请帮忙,测试表单是一个非常重要的过程,不能忽视。
正如@slax57所说,这是有问题的包装器解决方法。
出于我仍然未知的原因,在测试环境中“正在加载react-hook-form的esm和更改版本”。
解决方案是将以下行添加到
vite.config.js
文件中。
resolve: {
alias: {
'react-hook-form': require.resolve('react-hook-form'),
}
}