Material-ui: onChange isn't called when simulating click on Switch using enzyme

Created on 9 Jan 2018  路  2Comments  路  Source: mui-org/material-ui

  • [x] I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior


Simulating click on a mounted switch control should call onChange

Current Behavior


onChange isn't called.

Steps to Reproduce (for bugs)

class Toggle extends React.Component<ToggleProps> {
  private toggleChange = (event, checked) => {
    this.props.field.visible = checked;
  }

  render() {
    const value = this.props.field.visible ? 'on' : 'off';
    return (
      <div data-hook="toggle">
        <Switch
           value={value}
          checked={this.props.field.visible}
          onChange={this.toggleChange}
        />
      </div>
    );
  }
}

test:

wrapper = mount(<Toggle field={this.field}/>, {attachTo: document.createElement('div')});
input = () => wrapper.find('input')
on = () => input().props().value === 'on'

// these options do nothing
wrapper.simulate('click')
input().simulate('click')
// also tried this which throws
input().props().onChange()

TypeError: Cannot read property 'target' of undefined
      at Object.SwitchBase._this.handleInputChange [as onChange] (node_modules/material-ui/internal/SwitchBase.js:115:27)

Context

Your Environment

| Tech | Version |
|--------------|---------|
| Material-UI | 1.0.0-beta.27 |
| React | 16.2.0 |
| Enzyme | 3.3.0 |
| browser | chrome |
| etc | mac |

question test

Most helpful comment

I found a solution for this by simulating an explicit 'change' event with checked: true, but I'm really not sure if this is the proper way to test this. Any thoughts?

input().simulate('change', {target: {checked: !this.field.visible}});

All 2 comments

I found a solution for this by simulating an explicit 'change' event with checked: true, but I'm really not sure if this is the proper way to test this. Any thoughts?

input().simulate('change', {target: {checked: !this.field.visible}});

@salickc I think that you would experience the same behavior with a native checkbox. I don't think it's Material-UI related. But, yes. I think that it's the proper way to test it. We do something very close in our own tests.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

pola88 picture pola88  路  3Comments

finaiized picture finaiized  路  3Comments

ghost picture ghost  路  3Comments

ryanflorence picture ryanflorence  路  3Comments

mattmiddlesworth picture mattmiddlesworth  路  3Comments