useContext hook not working with shallow
- Dominant language
- JavaScript
- Stars
- 19.8k
- Forks
- 2k
- PR merge metrics
- No merged PRs in 30d
Description
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.
```jsx
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
};
it("renders the correct text", () => {
MyComponent.contextTypes = {
myVal: PropTypes.any
};
const wrapper = shallow(
,
{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
- [x] shallow
- [ ] mount
- [ ] render
#### Version
| library | version
| ------------------- | -------
| enzyme |
| react |
| react-dom |
| react-test-renderer |
| adapter (below) |
#### Adapter
- [x] enzyme-adapter-react-16
- [ ] enzyme-adapter-react-16.3
- [ ] enzyme-adapter-react-16.2
- [ ] enzyme-adapter-react-16.1
- [ ] enzyme-adapter-react-15
- [ ] enzyme-adapter-react-15.4
- [ ] enzyme-adapter-react-14
- [ ] enzyme-adapter-react-13
- [ ] enzyme-adapter-react-helper
- [ ] others ( )
Contributor guide
Research direction
Reproduce the minimal case from the issue in the `index.spec.js` example, comparing `shallow` with `mount` and the Provider/`dive()` variant. Use the `class.spec.js` workaround as a comparison point; the issue is done when `useContext` returns the supplied value during shallow rendering and the expected text is `foobar`.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- testing
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100