Change:
We need a way to test the output of a single level React component without resolving it all the way down to the bottom layer (whatever that is). I'm thinking something like this: Basically, this fix needs to go through the entire life-cycle of ReactCompositeComponent. It just needs to bail out whenever it would've continued rendering.
Reopened so that we can track the remaining features (refs etc.)
Weird, I thought GitHub only closed issues if you used language like "fixes #NNNN", not if you simply mentioned the issue at all. Sorry about that.
The PR text included "WIP to "
Is the rest (refs support) blocked by or can more work be done now?
Any reason this doesn't support other than that it's not implemented yet? I was hoping to do something like
that's supposed to work. Can you post a minimal repro?
How do you do this?  does not return an instance.
It works if I use so I think could just return that from . (I also have to shim because React expects it to be defined for some reason.)
Finding this quite useful. But it has been a bit inconvenient to have among the children when an element is conditionally rendered.
The idea was to make the helpers ignore null which could help with that. Perhaps we could have return an iterable which traverses nested arrays and ignores null.
Really? Allowing nulls was a change intentionally introduced a long time ago. In I have an implementation of toArray.
Allowing empty children (null, undefined, boolean) was a controversial topic, where we eventually landed on null/boolean/undefined being passed through. That way you could explicitly treat an empty slot as something special. This landed very early on before we really started seeing pattern developing. However, IMO, we've seen that this leads to inconsistent implementations where null slots will break and is not possible to use. It is unclear whether a set of children allows nullable slots, and if they do, it is unclear what that means. For example, in a grid layout component, does an empty slot mean that there should be an empty column in the grid, or that it should be skipped? Therefore, a lot of our components end up with explicit null checks. Meaning boilerplate, and inconsistent behavior when they're forgotten. Therefore, I think the default should be to filter out nulls which is consistent with the behavior of the built-ins components. It is still possible to get access to the raw data if you have a different type of children in mind where empty slots is meaningful.
How should this work with the TestUtils functions. For example, this fails: I can't see any other info on mentioned at the start of this issue, is this what I'm missing? My end goal is simply to test that if I pass in 10 articles then 10 components get rendered. Any help would be awesome.
Hi David, the and functions are meant to be used with the output of , not shallow rendering. React doesn't currently provide a helper that will traverse trees for you. Your options for now are to describe the structure of the tree explicitly as in lines 4-5 of your example, or write your own helper module to find descendants you care about. hasn't been implemented yet. Refer to the for what's actually in React.
Cool, thanks for the reply I've returned to just using since the components I'm testing (and their children) don't have state/stores so don't really need mocking out anyway. One last (maybe stupid) question, what does mean?
So, I am trying to use Shallow Rendering and have it mostly only thing left I can’t figure out is the recommended way to mock events and how to get with events to pass. I've attempted to use the method directly from the in the test (). This seems dirty…is there a way to just say or something? I could post this on Stack Overflow, but I have had very little luck finding good information about Shallow Rendering online. If anyone has experience with shallow rendering and can give me some help you will be my hero... Source code: ! !
If I have an issue with shallow rendering, should I create a new issue, or post it here?
New issue please.
you might find that helps in providing higher-level assertions for the sort of thing you're doing there. In that particular case, I would avoid asserting on the event handler of the anchor in that test - but a different test would want to call to test the handler.
Super late reply, but "scry" is a fancy word for "find". I'm not sure why we don't just use "find". Maybe to avoid confusion between the plural and singular forms, whose names would otherwise differ only by one "s".
scry is because of legacy internal FB APIs. No reason.
Like I'm keenly on the lookout for a way to correctly unit test event handling in React code. Is there any documentation that anyone could point me to? I've looked at but it didn't seem to have something that scratches my particular itch. Here's my scenario (cut down): Where Problem looks like this: I'd like to be able to assert that is wired up for my component but I'm at a loss as to how to do that....
What you actually want is to assert that clicking interacts with the router. Pass in a fake context with a router mock (try Simon) then call Apologies for the brevity, on a phone.
Hi Thanks for responding. I'm not too clear on how to mock successfully when it comes to context. Digging through the source of I came up with this: However this dies a death with: Which makes me think I'm getting the context mocking wrong. Do you know how you successfully mock context with ? I'm using Jasmine (as you probably guessed!) I have a feeling I'm close...
Are you using React 0.13? You're probably hitting the difference between parent & owner context. Skin deep has a wrapper that helps with this - there's a context example the test suite, but the short answer is to wrap your render in another function call and let skin deep set up the context. This problem should go away in 0.14
I am using React 0.13, yes. If I port to 0.14 this issue should resolve? I might give that a crack if that's the case (it is in RC after all)
Problems with the upgrade. I have raised . Will have to return to this later I think.
I have written and as companion tools when testing with shallow rendering. It gives you the ability to diff on JSX strings rendered instead of React element objects.
Hi, I was wondering what was the state of: simulating events when using shallow rendering using refs when using shallow rendering How can we help make this happen if that's still planned?
This issue is pretty stale so I’ll close it. If there are specific features you miss in the shallow renderer please create new issues with proposals on how they should work. Note that we a new that is much more feature-complete.

Discussion:
/** * @private */ <ins> _renderValidatedComponentWithoutOwnerOrContext: function() { var inst = this._instance; var renderedComponent = inst.render(); if (__DEV__) { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ </ins> _renderValidatedComponent: ReactPerf.measure( 'ReactCompositeComponent', '_renderValidatedComponent',

ReactCurrentOwner.current = this; var inst = this._instance; try { <del> renderedComponent = inst.render(); if (__DEV__) { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } </del> <ins> renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); </ins> } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null;

}); <ins> var ShallowMixin = assign({}, ReactCompositeComponentMixin, { /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {ReactElement} Shallow rendering of the component. * @final * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); var inst = this._instance; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING; // No context for shallow-mounted components. inst.props = this._processProps(this._currentElement.props); var initialState = inst.getInitialState ? inst.getInitialState() : null; if (__DEV__) { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && inst.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', inst.constructor.displayName || 'ReactCompositeComponent' ); inst.state = initialState; this._pendingState = null; this._pendingForceUpdate = false; if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingState` without triggering a re-render. if (this._pendingState) { inst.state = this._pendingState; this._pendingState = null; } } // No recursive call to instantiateReactComponent for shallow rendering. this._renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); // Done with mounting, `setState` will now trigger UI changes. this._compositeLifeCycleState = null; // No call to this._renderedComponent.mountComponent for shallow // rendering. if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return this._renderedComponent; }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function(transaction) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; // Use the without-owner-or-context variant of _rVC below: var nextRenderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { prevComponentInstance.receiveComponent( nextRenderedElement, transaction ); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; // Don't unmount previous instance since it was never mounted, due to // shallow render. //prevComponentInstance.unmountComponent(); this._renderedComponent = nextRenderedElement; // ^ no instantiateReactComponent // // no recursive mountComponent return nextRenderedElement; } } }); </ins> var ReactCompositeComponent = { LifeCycle: CompositeLifeCycle, <del> Mixin: ReactCompositeComponentMixin </del> <ins> Mixin: ReactCompositeComponentMixin, ShallowMixin: ShallowMixin </ins> };

// an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. <del> this._store = { validated: false, props: props }; </del> <ins> this._store = { props: props }; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; </ins> // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing

var React = require('React'); var ReactElement = require('ReactElement'); var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); <ins> var ReactCompositeComponent = require('ReactCompositeComponent'); var ReactInstanceHandles = require('ReactInstanceHandles'); </ins> var ReactInstanceMap = require('ReactInstanceMap'); var ReactMount = require('ReactMount'); var ReactUpdates = require('ReactUpdates'); var SyntheticEvent = require('SyntheticEvent'); var assign = require('Object.assign'); <ins> var instantiateReactComponent = require('instantiateReactComponent'); </ins> var topLevelTypes = EventConstants.topLevelTypes;

}; }, <ins> createRenderer: function() { return new ReactShallowRenderer(); }, </ins> Simulate: null, SimulateNative: {} }; /** <ins> * @class ReactShallowRenderer */ var ReactShallowRenderer = function() { this._instance = null; }; ReactShallowRenderer.prototype.getRenderOutput = function() { return (this._instance && this._instance._renderedComponent) || null; }; var ShallowComponentWrapper = function(inst) { this._instance = inst; } assign( ShallowComponentWrapper.prototype, ReactCompositeComponent.ShallowMixin ); ReactShallowRenderer.prototype.render = function(element) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); this._render(element, transaction); ReactUpdates.ReactReconcileTransaction.release(transaction); }; ReactShallowRenderer.prototype._render = function(element, transaction) { if (!this._instance) { var rootID = ReactInstanceHandles.createReactRootID(); var instance = new ShallowComponentWrapper(new element.type(element.props)); instance.construct(element); instance.mountComponent(rootID, transaction, 0); this._instance = instance; } else { this._instance.receiveComponent(element, transaction); } }; /** </ins> * Exports: * * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)`

<ins> /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ "use strict"; var React; var ReactTestUtils; var mocks; var warn; describe('ReactTestUtils', function() { beforeEach(function() { mocks = require('mocks'); React = require('React'); ReactTestUtils = require('ReactTestUtils'); warn = console.warn; console.warn = mocks.getMockFunction(); }); afterEach(function() { console.warn = warn; }); it('should have shallow rendering', function() { var SomeComponent = React.createClass({ render: function() { return ( <div> <span className="child1" /> <span className="child2" /> </div> ); } }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(<SomeComponent />); var result = shallowRenderer.getRenderOutput(); expect(result.type).toBe('div'); expect(result.props.children).toEqual([ <span className="child1" />, <span className="child2" /> ]); }); it('lets you update shallowly rendered components', function() { var SomeComponent = React.createClass({ getInitialState: function() { return {clicked: false}; }, onClick: function() { this.setState({clicked: true}); }, render: function() { var className = this.state.clicked ? 'was-clicked' : ''; if (this.props.aNew === 'prop') { return ( <a href="#" onClick={this.onClick} className={className}> Test link </a> ); } else { return ( <div> <span className="child1" /> <span className="child2" /> </div> ); } } }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(<SomeComponent />); var result = shallowRenderer.getRenderOutput(); expect(result.type).toBe('div'); expect(result.props.children).toEqual([ <span className="child1" />, <span className="child2" /> ]); shallowRenderer.render(<SomeComponent aNew="prop" />); var updatedResult = shallowRenderer.getRenderOutput(); expect(updatedResult.type).toBe('a'); var mockEvent = {}; updatedResult.props.onClick(mockEvent); var updatedResultCausedByClick = shallowRenderer.getRenderOutput(); expect(updatedResultCausedByClick.type).toBe('a'); expect(updatedResultCausedByClick.props.className).toBe('was-clicked'); }); }); </ins>