The useContext hook does not work with shallow rendering and passing in context. Are there any workarounds for now?
Current behavior
The value returned by useContext in a function component appears to be empty when using shallow and passing in a context argument. (The same problem also occurs when wrapping the component in the appropriate context Provider directly and then calling .dive()).
Here is a minimal test case, also reproduced at https://codesandbox.io/s/nice-blackwell-yz7tn in the index.spec.js file.
import React, { useContext } from "react";
import PropTypes from "prop-types";
import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({ adapter: new Adapter() });
const MyContext = React.createContext({});
export const MyComponent = () => {
const { myVal } = useContext(MyContext);
return <div data-test="my-component">{myVal}</div>;
};
it("renders the correct text", () => {
MyComponent.contextTypes = {
myVal: PropTypes.any
};
const wrapper = shallow(
<MyComponent />,
{context: {myVal: 'foobar'}}
);
expect(wrapper.text()).toEqual("foobar"); // expected "foobar" received ""
});
Expected behavior
The text in the example above is expected to be "foobar", but it's actually "".
In general, the value returned from useContext appears to be undefined.
Note that using mount instead of shallow causes the test to pass.
Also note: the codesandbox above has a second file (class.spec.js) in which a hack is employed that makes the test pass, which uses the legacy contextTypes. But this only appears to work with classes and this.context, not with useContext.
Your environment
enzyme 3.10.0
enzyme-adapter-react-16 1.14.0
react 16.8.6
react-dom 16.8.6
API
Version
| library |
version |
| enzyme |
|
| react |
|
| react-dom |
|
| react-test-renderer |
|
| adapter (below) |
|
Adapter
The
useContexthook does not work withshallowrendering and passing incontext. Are there any workarounds for now?Current behavior
The value returned by
useContextin a function component appears to be empty when usingshallowand passing in acontextargument. (The same problem also occurs when wrapping the component in the appropriate context Provider directly and then calling.dive()).Here is a minimal test case, also reproduced at https://codesandbox.io/s/nice-blackwell-yz7tn in the
index.spec.jsfile.Expected behavior
The text in the example above is expected to be
"foobar", but it's actually"".In general, the value returned from
useContextappears to be undefined.Note that using
mountinstead ofshallowcauses the test to pass.Also note: the codesandbox above has a second file (
class.spec.js) in which a hack is employed that makes the test pass, which uses the legacycontextTypes. But this only appears to work with classes andthis.context, not withuseContext.Your environment
enzyme 3.10.0
enzyme-adapter-react-16 1.14.0
react 16.8.6
react-dom 16.8.6
API
Version
Adapter