Skip to content

Commit

Permalink
Add support for passing context to React class based components that …
Browse files Browse the repository at this point in the history
…request context via setting .contextType, according to patches posted in enzymejs#2189 (comment). Adds changes to ReactSixteenAdapter and simple test case.
  • Loading branch information
unverbraucht authored and pablopalacios committed Mar 18, 2022
1 parent 3d286a4 commit d2f48f9
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/enzyme-adapter-react-16/src/ReactSixteenAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,13 @@ class ReactSixteenAdapter extends EnzymeAdapter {
renderedEl = transformSuspense(renderedEl, renderedEl, { suspenseFallback });
const { type: Component } = renderedEl;

const context = getMaskedContext(Component.contextTypes, unmaskedContext);
let context;
if (Component.contextType) {
const Provider = adapter.getProviderFromConsumer(Component.contextType);
context = providerValues.has(Provider) ? providerValues.get(Provider) : getProviderDefaultValue(Provider);
} else {
context = getMaskedContext(Component.contextTypes, unmaskedContext);
}

if (isMemo(el.type)) {
const { type: InnerComp, compare } = el.type;
Expand Down
28 changes: 28 additions & 0 deletions packages/enzyme-test-suite/test/ShallowWrapper-spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,34 @@ describe('shallow', () => {
expect(consumer.text()).to.equal('foo');
});
});

describe('shallow() on Provider and Consumer through .contextType', () => {

const { Provider } = React.createContext('howdy!');

class OuterComponent extends React.Component {
render() {
return (
<Provider value="foo"><InnerComponent /></Provider>
);
}
}

class InnerComponent extends React.Component {
render() {
return this.context;
}
}

InnerComponent.contextType = Provider;

it('works on a Provider', () => {
const wrapper = shallow(<OuterComponent />);
const provides = wrapper.find(Provider).dive();
const provider = provides.find(InnerComponent).shallow();
expect(provider.text()).to.equal('foo');
});
});
});

describeIf(is('> 0.13'), 'stateless function components (SFCs)', () => {
Expand Down

0 comments on commit d2f48f9

Please sign in to comment.