Skip to content

useContext hook not working with shallowΒ #2176

@mstorus

Description

@mstorus

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

  • shallow
  • mount
  • render

Version

library version
enzyme
react
react-dom
react-test-renderer
adapter (below)

Adapter

  • 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 ( )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions