Skip to content

Instantly share code, notes, and snippets.

@pokorson
Created November 29, 2017 16:25
Show Gist options
  • Save pokorson/1a357c58d3f4e8101d92592bc0e3a050 to your computer and use it in GitHub Desktop.
Save pokorson/1a357c58d3f4e8101d92592bc0e3a050 to your computer and use it in GitHub Desktop.
React vs Recompose unit tests
export default class Counter extends React.Component {
state = {
counter: this.props.counter
};
increment = () => {
this.setState(state => ({
counter: state.counter + 1
}));
};
decrement = () => {
this.setState(state => ({
counter: state.counter - 1
}));
};
render() {
return (
<div>
{this.state.counter}
<button onClick={this.increment}>increment</button>
<button onClick={this.decrement}>decrement</button>
</div>
}
}
describe("Counter component", () => {
it("increments counter", () => {
const component = shallow(<Counter counter={5} />);
component.instance().increment();
expect(component.instance().state.counter).toEqual(6);
});
it("decrements counter", () => {
const component = shallow(<Counter counter={5} />);
component.instance().decrement();
expect(component.instance().state.counter).toEqual(4);
});
});
const CounterStatelessComponent = ({ counter, increment, decrement }) => {
return (
<div>
{counter}
<button onClick={increment}>increment</button>
<button onClick={decrement}>decrement</button>
</div>
);
};
const withCounter = compose(
withState("counter", "setCounter", 0),
mapProps(({ counter, setCounter }) => {
return {
counter,
increment: () => {
setCounter(counter + 1);
},
decrement: () => {
setCounter(counter - 1);
}
};
})
);
export const CounterStateless = withCounter(CounterStatelessComponent);
describe("Counter stateless", () => {
it("increments counter", () => {
const rootComponent = mount(<CounterStateless />);
let component = rootComponent.find("CounterStatelessComponent");
component.props().increment();
rootComponent.update();
component = rootComponent.find("CounterStatelessComponent");
expect(component.props().counter).toEqual(1);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment