Skip to content

Commit fc1c6f9

Browse files
author
Brian Vaughn
committed
Shallow renderer preserves state for cloned element
1 parent bf0583b commit fc1c6f9

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/renderers/dom/test/__tests__/ReactTestUtils-test.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,31 @@ describe('ReactTestUtils', () => {
779779
expect(hrs.length).toBe(2);
780780
});
781781

782+
it('should enable rendering of cloned element', () => {
783+
class SimpleComponent extends React.Component {
784+
constructor(props) {
785+
super(props);
786+
787+
this.state = {
788+
bar: 'bar',
789+
};
790+
}
791+
792+
render() {
793+
return <div>{`${this.props.foo}:${this.state.bar}`}</div>;
794+
}
795+
}
796+
797+
const shallowRenderer = createRenderer();
798+
let result = shallowRenderer.render(<SimpleComponent foo="foo" />);
799+
expect(result).toEqual(<div>foo:bar</div>);
800+
801+
const instance = shallowRenderer.getMountedInstance();
802+
const cloned = React.cloneElement(instance, {foo: 'baz'});
803+
result = shallowRenderer.render(cloned);
804+
expect(result).toEqual(<div>baz:bar</div>);
805+
});
806+
782807
describe('Simulate', () => {
783808
it('should set the type of the event', () => {
784809
let event;
@@ -796,5 +821,27 @@ describe('ReactTestUtils', () => {
796821
expect(event.type).toBe('keydown');
797822
expect(event.nativeEvent.type).toBe('keydown');
798823
});
824+
825+
it('should work with renderIntoDocument', () => {
826+
const onChange = jest.fn();
827+
828+
class MyComponent extends React.Component {
829+
render() {
830+
return <div><input type="text" onChange={onChange} /></div>;
831+
}
832+
}
833+
834+
const instance = ReactTestUtils.renderIntoDocument(<MyComponent />);
835+
const input = ReactTestUtils.findRenderedDOMComponentWithTag(
836+
instance,
837+
'input',
838+
);
839+
input.value = 'giraffe';
840+
ReactTestUtils.Simulate.change(input);
841+
842+
expect(onChange).toHaveBeenCalledWith(
843+
jasmine.objectContaining({target: input}),
844+
);
845+
});
799846
});
800847
});

src/renderers/testing/ReactShallowRenderer.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,8 @@ class ReactShallowRenderer {
151151
}
152152

153153
// Read state after cWRP in case it calls setState
154-
const state = this._newState || emptyObject;
154+
// Fallback to previous instance state to support rendering React.cloneElement()
155+
const state = this._newState || this._instance.state || emptyObject;
155156

156157
if (typeof this._instance.shouldComponentUpdate === 'function') {
157158
if (

0 commit comments

Comments
 (0)