如何模拟输入文本并输入在 Jest 中按下的键
How do I simulate text getting entered and enter key pressed in Jest
我有一个 material-ui 文本字段,我想在其中模拟用户输入并按回车键。我如何在玩笑中做到这一点?
我查看了相关答案,其中 none 对我有用。
尝试了以下方法:
const input = getByTestId('emailId').querySelector('input')
fireEvent.change(input, {
target: { value: 'abc' }
}); //Up to this point works
None 正在工作:
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 是 returns 文本字段的另一个组件:
<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 });
我有一个 material-ui 文本字段,我想在其中模拟用户输入并按回车键。我如何在玩笑中做到这一点? 我查看了相关答案,其中 none 对我有用。
尝试了以下方法:
const input = getByTestId('emailId').querySelector('input')
fireEvent.change(input, {
target: { value: 'abc' }
}); //Up to this point works
None 正在工作:
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 是 returns 文本字段的另一个组件:
<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 });