From fac467034e8de3915182c4b12532441a5bb44440 Mon Sep 17 00:00:00 2001 From: Toru Kobayashi Date: Wed, 4 Jul 2018 18:27:14 +0900 Subject: [PATCH] [Tests] `shallow`: add `componentDidUpdate` tests Per https://github.com/airbnb/enzyme/issues/1452#issuecomment-402421812 --- .../test/ShallowWrapper-spec.jsx | 50 +++++++++++++++---- 1 file changed, 41 insertions(+), 9 deletions(-) diff --git a/packages/enzyme-test-suite/test/ShallowWrapper-spec.jsx b/packages/enzyme-test-suite/test/ShallowWrapper-spec.jsx index e1ef33380..426f5b6cc 100644 --- a/packages/enzyme-test-suite/test/ShallowWrapper-spec.jsx +++ b/packages/enzyme-test-suite/test/ShallowWrapper-spec.jsx @@ -3351,8 +3351,8 @@ describe('shallow', () => { } } const result = shallow(, { lifecycleExperimental: true }); - expect(result.state('count')).to.equal(2); - expect(spy.callCount).to.equal(2); + expect(result.state()).to.have.property('count', 2); + expect(spy).to.have.property('callCount', 2); }); }); @@ -3382,19 +3382,17 @@ describe('shallow', () => { } render() { spy('render'); - return
{this.state.foo}
; + const { foo } = this.state; + return
{foo}
; } } Foo.contextTypes = { foo: PropTypes.string, }; - const wrapper = shallow( - , - { - context: { foo: 'context' }, - }, - ); + const wrapper = shallow(, { + context: { foo: 'context' }, + }); wrapper.setProps({ foo: 'baz' }); wrapper.setProps({ foo: 'bax' }); expect(spy.args).to.deep.equal([ @@ -3976,6 +3974,40 @@ describe('shallow', () => { }); }); + context('component instance', () => { + it('should call `componentDidUpdate` when component’s `setState` is called', () => { + const spy = sinon.spy(); + class Foo extends React.Component { + constructor(props) { + super(props); + this.state = { + foo: 'init', + }; + } + componentDidUpdate() { + spy(); + } + onChange() { + // enzyme can't handle the update because `this` is a ReactComponent instance, + // not a ShallowWrapper instance. + this.setState({ foo: 'onChange update' }); + } + render() { + return
{this.state.foo}
; + } + } + const wrapper = shallow(); + + wrapper.setState({ foo: 'wrapper setState update' }); + expect(wrapper.state('foo')).to.equal('wrapper setState update'); + expect(spy).to.have.property('callCount', 1); + + wrapper.instance().onChange(); + expect(wrapper.state('foo')).to.equal('onChange update'); + expect(spy).to.have.property('callCount', 2); + }); + }); + describeIf(REACT16, 'support getSnapshotBeforeUpdate', () => { it('should call getSnapshotBeforeUpdate and pass snapshot to componentDidUpdate', () => { const spy = sinon.spy();