Asking
Asking

Reputation: 4172

Test react dropdown using enzyme

I am using React js and Autocomplete component from @mui/material/Autocomplete. Here you can see how it works. https://codesandbox.io/s/silent-night-7id9z?file=/index.js .
I want to test this component using enzyme. My test looks like this:

import {mount} from "enzyme";
import AutocompleteComponent from "./Autocomplete";

describe('autocomplete', () => {
    test('should trigger on change', () => {
        const wrapper = mount(<AutocompleteComponent/>);
        const input = wrapper.find('input');

        input.simulate('change', 'John');
        expect(input.props('value')).toContain('John')
        console.log(input.debug())
    })
})

My component code looks like this:

const WithMaterialUI = () => {
  const [data, setData] = React.useState([]);
  return (
    <Autocomplete
      freeSolo
      disablePortal
      id="combo-box-demo"
      name="test"
      options={["2", "3"]}
      onInputChange={(_, val) => {
        setData(val);
      }}
      onChange={(_, val) => {
        setData(val);
      }}
      value={data}
      sx={{ width: 300 }}
      renderInput={(params) => (
        <TextField name="test" {...params} label="Movie" />
      )}
    />
  );
};

Running this test i got: Expected value: "John" Received object: {"aria-activedescendant": null, "aria-autocomplete": "list", "aria-controls": null, "aria-describedby": undefined, "aria-invalid": false, "autoCapitalize": "none", "autoComplete": "off", "autoFocus": false, "className": "MuiInputBase-input MuiInput-input MuiAutocomplete-input MuiAutocomplete-inputFocused MuiInputBase-inputAdornedEnd", "defaultValue": undefined, "disabled": false, "id": "combo-box-demo", "name": "test", "onAnimationStart": [Function handleAutoFill], "onBlur": [Function handleBlur], "onChange": [Function handleChange], "onFocus": [Function handleFocus], "onKeyDown": undefined, "onKeyUp": undefined, "onMouseDown": [Function handleInputMouseDown], "placeholder": undefined, "readOnly": undefined, "required": false, "rows": undefined, "spellCheck": "false", "type": "text", "value": "test"}.
How to test if the value is changed in the input and why my test failed?

Upvotes: 1

Views: 520

Answers (1)

Chenga
Chenga

Reputation: 68

I think this is how you need to simulate the change event:

input.simulate('change', { target: { value: 'Hello' } })

My source is: https://github.com/enzymejs/enzyme/issues/76#issuecomment-189606849

Upvotes: 1

Related Questions