我正在尝试为使用 Material UI 自动完成组件的组件编写测试。我不确定我做错了什么,但我的测试似乎没有触发 Material UI 自动完成组件的 onChange。
it('should render autocomplete and select a user', async () => {
searchContact.mockResolvedValueOnce({
data: {
value: [
{
displayName: 'Jan Travis',
userPrincipalName: 'JanT@email.uk',
},
{
displayName: 'Jon Test',
userPrincipalName: '',
},
{
displayName: 'Jay Test',
userPrincipalName: 'JayT@email.uk',
},
],
},
});
initialProps.activityName = 'some-activity';
initialProps.testId = 'contact-person[0]';
initialProps.fromType = 'planning-contact-person';
const { getByRole } = render(<AutoCompleteUserSearch {...initialProps} />);
const autocomplete = getByRole('textbox');
autocomplete.focus();
await act(async () => {
fireEvent.change(document.activeElement, { target: { value: 'Jay' } });
});
fireEvent.keyDown(document.activeElement, { key: 'ArrowDown' });
fireEvent.keyDown(document.activeElement, { key: 'Enter' });
await waitFor(() => {
expect(autocomplete.value).toEqual('Jay');
});
这是我的自动完成组件的样子
return (
<React.Fragment>
<Autocomplete
id={props.activityName ? props.activityName : props.id}
freeSolo
data-testid={props.testId ? props.testId : 'autocomplete'}
defaultValue=""
getOptionLabel={(option) => (typeof option === 'string' ? option : option.displayName)}
getOptionSelected={(option, value) => {
return option.displayName === value;
}}
filterOptions={(x) => x}
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
value={autoCompleteValue}
autoComplete
includeInputInList
options={[...autoCompleteOptions]}
filterSelectedOptions
clearOnEscape
onChange={(event, newValue, reason) => {
setAutoCompleteOptions(newValue ? [newValue, ...autoCompleteOptions] : autoCompleteOptions);
if (newValue) {
setAutoCompleteValue(newValue.displayName);
if (newValue.userPrincipalName) {
setSelectUserEmailAddress(newValue.userPrincipalName);
setUserEmailAddressError();
} else {
setUserEmailAddressError('This user does not have an email address');
}
}
if (reason === 'clear') {
setAutoCompleteValue('');
}
}}
size="small"
renderInput={(params) => (
<div ref={params.InputProps.ref}>
<Input
type="text"
label="Search user"
name={props.activityName ? props.activityName : props.name}
{...params.inputProps}
inputProps={{ 'aria-label': 'Search user' }}
onChange={(ev) => {
onChangeHandle(ev.target.value);
}}
/>
</div>
)}
renderOption={(option, { inputValue }) => {
const matches = match(option.displayName, inputValue);
const parts = parse(option.displayName, matches);
return (
<div>
{parts.map((part, index) => (
<span key={index} style={{ fontWeight: part.highlight ? 700 : 400 }}>
{part.text}
</span>
))}
</div>
);
}}
/>
自动完成中的 onChange 似乎没有被触发。不确定在测试中 keyDown 是否正常工作。
这是我正在调用的 Input onChange 中的 onChangeHandle 函数
const onChangeHandle = (e) => {
setAutoCompleteValue(e);
if (e !== '') {
if (e) {
searchContact(e)
.then((res) => {
setAutoCompleteOptions(res.data.value);
})
.catch(() => {});
}
}
};
任何帮助将不胜感激,谢谢。