【问题标题】:How do I simulate text getting entered and enter key pressed in Jest如何模拟输入文本并在 Jest 中按下输入键
【发布时间】:2021-05-11 13:26:40
【问题描述】:

我有一个 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}
                    />

【问题讨论】:

  • 可以肯定:你的意思是“模拟”还是“刺激”?
  • 显示被测代码
  • @slideshowp2 完成

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:

对我有用的是:

fireEvent.keyPress(input, { key: 'Enter', charCode: 13 });

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 2010-09-09
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多