Skip to content

Instantly share code, notes, and snippets.

@ActuallyACat
Created May 6, 2018 23:49
Show Gist options
  • Save ActuallyACat/26e4bc661be9e84d36eb91011d7bfeb9 to your computer and use it in GitHub Desktop.
Save ActuallyACat/26e4bc661be9e84d36eb91011d7bfeb9 to your computer and use it in GitHub Desktop.
import React from 'react';
import Enzyme, { shallow, mount } from 'enzyme';
import sinon from 'sinon';
import Adapter from 'enzyme-adapter-react-15.4';
Enzyme.configure({ adapter: new Adapter() });
class Child extends React.Component {
render() {
return (
<div>
<h2>Some more stuff here</h2>
<button onClick={() => this.props.onCtaClick}>
Clicked: {this.props.clickCount}
</button>
</div>
);
}
}
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {
parentClicked: 0,
childClicked: 0
}
}
render() {
return (
<div>
<h1>Yay I'm a test</h1>
<Child
clickCount={this.state.childClicked}
onCtaClick={() => {
this.setState((prevState, props) => ({
childClicked: prevState.childClicked + 1
})
)}} />
<button onClick={() => this.props.onCtaClick}>
Clicked: {this.state.parentClicked}
</button>
</div>
);
}
}
describe('Container testing', () => {
const wrapper = mount(<Container />);
const child = wrapper.find(Child);
const instance = wrapper.find(Container).children().instance();
it('should mount the component', () => {
expect(wrapper.find(Container)).toHaveLength(1);
});
it('should mount the component', () => {
expect(wrapper.find(Child)).toHaveLength(1);
});
it('should pass in the default clickCount', () => {
expect(wrapper.find(Child).props().clickCount).toBe(0);
});
it('PARENT: should say "Clicked: 0', () => {
expect(wrapper.find('button').first().text()).toEqual('Clicked: 0');
});
it('CHILD: should say "Clicked: 0', () => {
expect(wrapper.find(Child).find('button').text()).toEqual('Clicked: 0');
});
describe('clicking stuff', () => {
wrapper.find('button').at(0).prop('onClick')();
wrapper.find('button').at(1).prop('onClick')();
wrapper.find('button').at(0).simulate('click');
wrapper.find('button').at(1).simulate('click');
wrapper.find('button').at(0).props().onClick();
wrapper.find('button').at(1).props().onClick();
wrapper.update();
it('PARENT: should say "Clicked: 1', () => {
expect(wrapper.find('button').first().text()).toEqual('Clicked: 1');
});
it('CHILD: should say "Clicked: 1', () => {
console.log(wrapper.state());
expect(wrapper.find(Child).find('button').text()).toEqual('Clicked: 1');
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment