Skip to content

Instantly share code, notes, and snippets.

@mrwithersea
Created November 22, 2017 09:49
Show Gist options
  • Save mrwithersea/b93915739a854c20e45cac6f09397674 to your computer and use it in GitHub Desktop.
Save mrwithersea/b93915739a854c20e45cac6f09397674 to your computer and use it in GitHub Desktop.
Unit tests on a react-redux connected HOC
import { compose, lifecycle } from 'recompose';
import { connect } from 'react-redux';
import { getSomeState } from '../selectors';
import { doSomething } from '../actions';
export default compose(
connect(
(state) => ({
auth: getSomeState(state),
}),
(dispatch) => ({
do() {
return dispatch(doSomething());
},
})
),
lifecycle({
componentWillUpdate(props) {
if (!props.foo.bar) {
props.do();
}
},
})
);
import test from 'tape';
import React from 'react';
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import enhanceWithX, { __RewireAPI__ } from './enhance-with-x';
test('enhance with X HOC', assert => {
assert.plan(1);
const fakeAction = 'fake action';
__RewireAPI__.__Rewire__('getSomeState', state => state);
__RewireAPI__.__Rewire__('doSomething', () => fakeAction);
let updateConnectedComponent;
let fakeState = { foo: { bar: 'cheese' }};
const fakeStore = {
getState: () => fakeState,
subscribe: (cb) => updateConnectedComponent = cb,
dispatch: (actual) => {
const expected = fakeAction;
assert.equal(actual, expected,
`given a component is enhanced with X then it should dispatch an action when the state updates`);
__RewireAPI__.__ResetDependency__('doSomething');
__RewireAPI__.__ResetDependency__('getSomeState');
},
};
const FakeComponent = () => <p>Fake component</p>;
const Target = enhanceWithX(FakeComponent);
mount(<Provider store={fakeStore}><Target /></Provider>);
fakeState = { foo: {} };
updateConnectedComponent();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment