使用 Controller API 测试 Enzyme 和 jest 中 Select 的 React-form-hook
我想测试我的下面的选择并模拟更改事件。但目前 onchange 不起作用。从下拉列表中选择某些选项时,我想显示一个输入字段,但无法模拟 onchange 事件。 JSX 文件中的一切工作正常。但无法在测试文件中正确模拟。
const accType = watch('accountType');
<Controller
control={control}
name="accountType"
label="Account Type"
rules={{ required: true }}
render={({ onChange, ref }) => (
<Select
onChange={(e) => onChange(e.target.value)}
className={styles.w100}
defaultValue={bankAccountTypes[0]}
>
{bankAccountTypes.map((type) => (
<MenuItem key={type} value={type}>
{type}
</MenuItem>
))}
</Select>
)}
/>
{
accType === 'NRO Savings Account' ? (
<Grid item={true} xs={12} className={`${styles.fieldItem}`}>
<TextField
InputLabelProps={{ shrink: true }}
className={styles.w100}
type="text"
name="country"
required={true}
label="Country"
inputRef={register({ required: true })}
/>
</Grid>
) : null
}
下面是我的测试文件
// Country Field should be hidden
let country = component.find({ name: 'country' });
expect(country).toHaveLength(0);
// Simulate Account type field to display Country Dropdown
await act(async () => {
accountType.simulate('change', { value: 'NRO Savings Account' });
});
// Country field should be present now
country = component.find({ name: 'country' });
expect(country).toHaveLength(1);
//Expected length: 1
//Received length: 0
我在 React 中使用 Jest 和 Enzyme
I want to test my below Select and simulate on change event. but currently the onchange is not working. On selecting certain option from the dropwdown, I wan to show a Input field but I am unable to simulate onchange event. Everything is working fine in the JSX file. but not getting simulated properly in the Test File.
const accType = watch('accountType');
<Controller
control={control}
name="accountType"
label="Account Type"
rules={{ required: true }}
render={({ onChange, ref }) => (
<Select
onChange={(e) => onChange(e.target.value)}
className={styles.w100}
defaultValue={bankAccountTypes[0]}
>
{bankAccountTypes.map((type) => (
<MenuItem key={type} value={type}>
{type}
</MenuItem>
))}
</Select>
)}
/>
{
accType === 'NRO Savings Account' ? (
<Grid item={true} xs={12} className={`${styles.fieldItem}`}>
<TextField
InputLabelProps={{ shrink: true }}
className={styles.w100}
type="text"
name="country"
required={true}
label="Country"
inputRef={register({ required: true })}
/>
</Grid>
) : null
}
Below is my Test file
// Country Field should be hidden
let country = component.find({ name: 'country' });
expect(country).toHaveLength(0);
// Simulate Account type field to display Country Dropdown
await act(async () => {
accountType.simulate('change', { value: 'NRO Savings Account' });
});
// Country field should be present now
country = component.find({ name: 'country' });
expect(country).toHaveLength(1);
//Expected length: 1
//Received length: 0
I am using Jest and Enzyme here in React
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论