javascriptreactjsjestjsreact-testing-library

How do I simulate text getting entered and enter key pressed in Jest


I have a material-ui textfield on which I want to simulate the user types in and hit enter. How do I do it in Jest? I went through related answers and none of them are working for me.

Tried the following:

        const input = getByTestId('emailId').querySelector('input')
        fireEvent.change(input, {
            target: { value: 'abc' }
        }); //Up to this point works

None of the following are working:

        fireEvent.submit(getByTestId('emailId').querySelector('input'));
        input.dispatchEvent(new KeyboardEvent('keydown',{'key':'Enter'}));
        getByTestId('emailId').querySelector('input').simulate('keydown', {key: 'Enter'})

The code under Test is:

<CustomTextField
                data-testid="emailId"
                textLabel={t('email', 'Email')}
                autocomplete="email"
                value={userEmail}
                onChange={onEmailchange}
                handleKeyHandler={submitOnEnter}
                autoFocus
            />

CustomTextField is another component that returns a textfield:

 <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}
                    />

Solution

  • Well what worked for me is this:

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