Skip to content

Commit

Permalink
Throw away old shallow renderer state on type change
Browse files Browse the repository at this point in the history
This worked in function components but was broken for classes. It incorrectly retained the old instance even if the type was different.
  • Loading branch information
gaearon committed Mar 15, 2019
1 parent b283d75 commit 50f2262
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/react-test-renderer/src/ReactShallowRenderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ class ReactShallowRenderer {
};

constructor() {
this._reset();
}

_reset() {
this._context = null;
this._element = null;
this._instance = null;
Expand Down Expand Up @@ -514,6 +518,9 @@ class ReactShallowRenderer {
if (this._rendering) {
return;
}
if (this._element != null && this._element.type !== element.type) {
this._reset();
}

const elementType = isMemo(element.type) ? element.type.type : element.type;
const previousElement = this._element;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1565,4 +1565,46 @@ describe('ReactShallowRenderer', () => {
'forwardRef requires a render function but was given object.',
);
});

it('should let you change type', () => {
function Foo({prop}) {
return <div>Foo {prop}</div>;
}
function Bar({prop}) {
return <div>Bar {prop}</div>;
}

const shallowRenderer = createRenderer();
shallowRenderer.render(<Foo prop="foo1" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Foo {'foo1'}</div>);
shallowRenderer.render(<Foo prop="foo2" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Foo {'foo2'}</div>);
shallowRenderer.render(<Bar prop="bar1" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Bar {'bar1'}</div>);
shallowRenderer.render(<Bar prop="bar2" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Bar {'bar2'}</div>);
});

it('should let you change class type', () => {
class Foo extends React.Component {
render() {
return <div>Foo {this.props.prop}</div>;
}
}
class Bar extends React.Component {
render() {
return <div>Bar {this.props.prop}</div>;
}
}

const shallowRenderer = createRenderer();
shallowRenderer.render(<Foo prop="foo1" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Foo {'foo1'}</div>);
shallowRenderer.render(<Foo prop="foo2" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Foo {'foo2'}</div>);
shallowRenderer.render(<Bar prop="bar1" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Bar {'bar1'}</div>);
shallowRenderer.render(<Bar prop="bar2" />);
expect(shallowRenderer.getRenderOutput()).toEqual(<div>Bar {'bar2'}</div>);
});
});

0 comments on commit 50f2262

Please sign in to comment.