我有一个 Material-ui 文本字段,我想在其中模拟用户输入并按 Enter 键。我该如何在 Jest 中做到这一点? 我查看了相关答案,但没有一个对我有用。
尝试了以下方法:
const input = getByTestId('emailId').querySelector('input')
fireEvent.change(input, {
target: { value: 'abc' }
}); //Up to this point works
以下均无效:
fireEvent.submit(getByTestId('emailId').querySelector('input'));
input.dispatchEvent(new KeyboardEvent('keydown',{'key':'Enter'}));
getByTestId('emailId').querySelector('input').simulate('keydown', {key: 'Enter'})
测试中的代码是:
<CustomTextField
data-testid="emailId"
textLabel={t('email', 'Email')}
autocomplete="email"
value={userEmail}
onChange={onEmailchange}
handleKeyHandler={submitOnEnter}
autoFocus
/>
CustomTextField 是另一个返回文本字段的组件:
<TextField
size="small"
data-testid="emailId"
id={textFieldId || 'defaultTextFieldId'}
label={textLabel}
variant="outlined"
fullWidth
onChange={handleOnchange}
onBlur={onBlur}
value={value}
inputRef={txtField}
autoComplete={autocomplete}
autoFocus={autoFocus}
type={textFieldType}
onKeyPress={handleKeyHandler}
InputLabelProps={{
classes: {
root: classes.customLabelStyle,
focused: classes.cssFocused
}
}}
InputProps={{
classes: {
root: classes.cssOutlinedInput,
focused: classes.cssFocused,
notchedOutline: classes.notchedOutline
},
endAdornment: showSearchIcon ? inputAdornment : null
}}
{...textFieldProps}
/>
对我有用的是:
fireEvent.keyPress(input, { key: 'Enter', charCode: 13 });
keyPress
现已弃用,因此使用 keyDown
对我有用
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', keyCode: 13 });