Skip to content

Context is read by components regardless of contextTypes definition #1590

@wojtekmaj

Description

@wojtekmaj

Consider the following, simplified example:

class NotGonnaRead extends Component {
  render() {
    return (
      <p>My favorite color is {this.context.favoriteColor}</p>
    );
  }
}

class WillRead extends Component {
  render() {
    return (
      <p>My favorite color is {this.context.favoriteColor}</p>
    );
  }
}

WillRead.contextTypes = {
  favoriteColor: PropTypes.string,
}

class FavoriteColorProvider extends Component {
  getChildContext() {
    return {
      favoriteColor: 'purple',
    };
  }
}

If we render it like so:

<FavoriteColorProvider>
    <NotGonnaRead />
</FavoriteColorProvider>

then the output is going to be My favorite color is .

Rendering this, however:

If we render it like so:

<FavoriteColorProvider>
    <WillRead />
</FavoriteColorProvider>

will correctly output My favorite color is purple.

Current behavior

If we would like to test if NotGonnaRead component is behaving properly (which it isn't), we would need to do something along the lines:

shallow(
  <NotGonnaRead />,
  { context: { favoriteColor: 'purple' } }
);

This will render <p>My favorite color is purple</p>.

Expected behavior

This example should render <p>My favorite color is </p> as contextTypes are not correctly defined.

Your environment

API

  • shallow
  • mount
  • render

Version

library version
Enzyme 3.3.0
React 16.2.0

Adapter

  • enzyme-adapter-react-16 1.1.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

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions