Cannot simulate enzyme events when wrapping components in react-with-styles
jamiesunderland opened this issue · comments
It's impossible to test for component events in enzyme when wrapping components with react-with-styles. I wasn't sure if I should submit this here or in enzyme but this seems more related to withStyles.
import React from 'react';
import { css, withStyles } from './withStyles';
class MyComponent extends React.Component {
constructor(props) {
this.state = {
toggled: false,
};
}
onClick() {
this.setState({toggled: !this.state.toggled});
}
return (
if (this.state.toggled) {
return (
<div className='clickable' onClick={this.onClick.bind(this)}>
<div {...css(withStylesStyles.container)}>
<span className='toggled'>Toggled</span>
</div>
</div>
);
}
return (
<div className='clickable' onClick={this.onClick.bind(this)}>
<div {...css(withStylesStyles.container)}>
<span className='not-toggled'>Not Toggled</span>
</div>
</div>
);
}
export default withStyles(({ color, unit }) => ({
container: {
color: color.primary,
marginBottom: 2 * unit,
},
}), { stylesPropName: 'withStylesStyles' })(MyComponent);
import { expect } from 'chai';
import { shallow } from 'enzyme';
import React from 'react';
describe('MyComponent', () => {
describe('#onClick', () => {
//Does not work
it('should display the toggled content after being clicked for the first time', () => {
const wrapper = shallow(<MyCompoent />);
expect(wrapper.html()).to.contain('.not-toggled');
wrapper.dive().find('.clickable').prop('onClick')();
expect(wrapper.html()).to.contain('.toggled');
});
});
});
I have the same problem with setState...
ModifNotifZoneComponent :
... render(){
return (
<div>
expended: {JSON.stringify(expended)}
</div>
)
}
and export this way :
export default withStyles(buttonStyles)(ModifNotifZoneComponent);
Test is :
it('renders correctly if snackbar', () => {
const component = createMount()(<ModifNotifZoneComponent {...shownProps} />);
component.setState({ expended: true })
let tree = component.html();
expect(tree).toMatchSnapshot();
});
renders in snapshot :
<div>
expended: false
</div>
In general, simulate
is a terrible API and I strongly discourage its use. Either way, I don't think this is a react-with-styles question, as it would likely happen with any HOC.
You need const wrapper = shallow(< MyComponent />).dive();
- one .dive
per HOC.
@nsaubi your issue seems different, but also is enzyme-related and not react-with-styles related, so please file an issue there.