Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking of material-ui select component with jest

I created a React component which i'm trying to test with React Testing Library. In my component i have following select component and its change handler

Component.jsx

<SingleSelect
  name="filter"
  label="Status"
  value={this.state.weatherStatus}
  options={this.state.weatherStatusOptions}
  onChange={this.handleFilterChange}
  testId="status"
/>

onChange handleFilterChange function

handleFilterChange = (event) => {
  this.setState({ weatherStatus: event.value });
}

An example of passing value this.state.weatherStatus is { id: 1, text: "cool weather"} For this I tried to write a mockup like below.

jest.mock('@material-ui/core/Select', () => props => (
  <div>
    <input
      onChange={(e) => props.onChange({ target: { value: e.target.value }})}
      value={props.value}
      data-testid={props['data-testid']}
    />
    {props.children}
  </div>
));

fireEvent.change(getByTestId('select'), { target: { value: { id: 1, text: "cool" } } });
expect(getByTestId('select').value).toEqual({ id: 1, text: "cool" });

But it is not working at all. any suggestion?

like image 917
Mani Avatar asked Oct 26 '25 10:10

Mani


1 Answers

it's definitely possible. I just managed to cracked it.

jest.mock('@material-ui/core/Select', () => (...rest)=> {
   return(  
     <div>
       <input
         data-testid='mock-component'
       />
   </div>
   )
 });

You just need to put it above the describe.

like image 90
khousuylong Avatar answered Oct 28 '25 23:10

khousuylong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!