Skip to content

Dive shallow in a Context Consumer #1908

@flackou

Description

@flackou

Hi,

Current behavior

I'm trying to dive into a Component wrapped with a HOC that adds a Context Consumer but I get an error TypeError: ShallowWrapper::dive() can only be called on components. Here is my test case to reproduce :

import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

const ThemeContext = React.createContext('light');

const withTheme = (Component) => {
  class ComponentWithTheme extends React.Component {
    render() {
      return (
        <ThemeContext.Consumer>
          {theme => <Component {...this.props} theme={theme} />}
        </ThemeContext.Consumer>
      );
    }
  }
  ComponentWithTheme.displayName = `withTheme(${Component.displayName || Component.name})`;
  return ComponentWithTheme;
}

class MyComponent extends React.Component {
  render() {
    const { theme } = this.props;
    return <div>{theme}</div>;
  }
}
const MyComponentWithTheme = withTheme(MyComponent);

const wrapper = shallow(<MyComponentWithTheme />, { context: 'dark' }).dive(); // TypeError

I'm not familiar with React Contexts, but it seems related to the "function as a child", which is however the regular way to use contexts (cf Context.Consumer in React doc).

Expected behavior

In my test case, the dive should succeed and return a wrapper around <div>dark</div> I guess.

Your environment

My package.json :

{
  "dependencies": {
    "react": "^16.5.1",
    "react-dom": "^16.6.3"
  },
  "devDependencies": {
    "@babel/core": "^7.1.6",
    "@babel/node": "^7.0.0",
    "@babel/preset-env": "^7.1.6",
    "@babel/preset-react": "^7.0.0",
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.7.0"
  }
}

API

  • shallow

Version

library version
enzyme 3.7.0
react 16.5.1
react-dom 16.6.3
react-test-renderer 16.3.2
adapter (below) 1.7.0

Adapter

  • enzyme-adapter-react-16

Am I getting something wrong ? Is there anything particular to do when "shallow diving" in a Context Consumer ? I can't see where's my error on this case so any help would be appreciated !

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