react-router icon indicating copy to clipboard operation
react-router copied to clipboard

State mixin causes jest to fail

Open jkschneider opened this issue 11 years ago • 7 comments

Jest seems to fail on the State mixin which uses this.context heavily.

image

So it does not appear to be possible to test any React component that involves the State mixin.

The class under test that is failing is defined like so:

var Router = require('react-router');
module.exports = React.createClass({
  mixins: [Router.State],
  ...
});

jkschneider avatar Jan 03 '15 20:01 jkschneider

You can force a context on the rendered component under test like so:

var Context = {
  getCurrentParams: function() {
    return { moduleName: 'Test' };
  }
};

var Downstream = React.withContext(Context, function() {
  return TestUtils.renderIntoDocument(<DownstreamComponent/>);
});

jkschneider avatar Jan 03 '15 21:01 jkschneider

FYI, withContext will get deprecated in next versions of React, but you'll be able to do the same by just wrapping your component into component with context.

gaearon avatar Jan 03 '15 21:01 gaearon

@gaearon could you give some more information on how the wrapping would work exactly? Maybe using the above example?

alengel avatar Jun 13 '15 05:06 alengel

@alengel any luck?

mmahalwy avatar Jun 21 '15 21:06 mmahalwy

var Context = {
  getCurrentParams: function() {
    return { moduleName: 'Test' };
  }
};

// React 0.13
var Wrapper = React.createClass({
  childContextTypes: {
    getCurrentParams: React.PropTypes.func.isRequired
  },
  getChildContext: function() {
    return Context;
  },
  render: function() {
    // React 0.13 uses owner-based context, so Wrapper has to render children here
    return this.props.render();
  }
});

var Downstream = TestUtils.renderIntoDocument(
  <Wrapper render={function() { return <DownStreamComponent />; }} />
);

// React 0.14?
var Wrapper = React.createClass({
  childContextTypes: {
    getCurrentParams: React.PropTypes.func.isRequired
  },
  getChildContext: function() {
    return Context;
  },
  render: function() {
    // context is based on parent, so it doesn't matter who created the element
    return this.props.children;
  }
});

var Downstream = TestUtils.renderIntoDocument(
  <Wrapper><DownStreamComponent /></Wrapper>
);

agundermann avatar Jun 21 '15 23:06 agundermann

Thanks for that @taurose!

mattdell avatar Dec 02 '15 13:12 mattdell

@taurose You just saved me a huge amount of time. Thank you very much!

If you're in Australia sometime, I'll shout you a beverage of your choice.

CaseyLeask avatar Feb 17 '16 06:02 CaseyLeask