Skip to content

Instantly share code, notes, and snippets.

@agiveygives
Created April 25, 2019 01:17
Show Gist options
  • Save agiveygives/b291602f679ab275f5feee0acbd2fd0e to your computer and use it in GitHub Desktop.
Save agiveygives/b291602f679ab275f5feee0acbd2fd0e to your computer and use it in GitHub Desktop.
Testing React State with React Class, Jest, and Enzyme
import React from 'react';
class TestComponent extends React.PureComponent {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<h3>{this.state.count}</h3>
<span>
<button id="count-up" type="button" onClick={() => this.setState({ count: this.state.count + 1 })}>
Count Up!
</button>
<button id="count-down" type="button" onClick={() => this.setState({ count: this.state.count - 1 })}>
Count Down!
</button>
<button id="zero-count" type="button" onClick={() => this.setState({ count: 0 })}>Zero</button>
</span>
)
}
}
export default TestComponent;
import React from 'react';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import TestComponent from './ClassComponent';
Enzyme.configure({ adapter: new Adapter() });
describe('<TestComponent />', () => {
let wrapper;
beforeEach(() => {
wrapper = Enzyme.shallow(<TestComponent />);
});
it('has the initial state count of zero', () => {
expect(wrapper.state()).toEqual({ count: 0 });
})
describe('The Count Up Button', () => {
it('increments state count by 1 on click', () => {
wrapper.find('#count-up').props().onClick();
expect(wrapper.state()).toEqual({ count: 1 });
});
});
describe('The Count Down Button', () => {
it('decrements state count by 1 on click', () => {
wrapper.find('#count-down').props().onClick();
expect(wrapper.state()).toEqual({ count: -1 });
});
});
describe('The Count Zero Button', () => {
it('sets state count to 0 on click', () => {
wrapper.setState({ count: 10 });
wrapper.find('#zero-count').props().onClick();
expect(wrapper.state()).toEqual({ count: 0 });
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment