Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created September 4, 2018 01:43
Show Gist options
  • Save AndrewRayCode/7221fa4b80d0092fac759be9fc1cf44c to your computer and use it in GitHub Desktop.
Save AndrewRayCode/7221fa4b80d0092fac759be9fc1cf44c to your computer and use it in GitHub Desktop.

Revisions

  1. AndrewRayCode created this gist Sep 4, 2018.
    19 changes: 19 additions & 0 deletions async.willmount.test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    import { spy } from 'sinon';
    import { shallow } from 'enzyme';

    // Utility method to asynchronously wait for component's willMount function to
    // complete. Requires the componentWillMount method *returns* its async promise
    // to wait for
    export const willMount = async unmountedComponent => {
    // Spy on the willmount method
    const lifecycleMethod = spy(unmountedComponent.type.prototype, 'componentWillMount');
    const wrapper = shallow(unmountedComponent);

    // Wait for the return value of the spy (the promise returned in
    // componentWillMount) and then undo the mock
    await lifecycleMethod.returnValues[0];
    lifecycleMethod.restore();

    // Update component so async changes take place
    return wrapper.update();
    };
    12 changes: 12 additions & 0 deletions usage.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    class MyComponent extends Component {
    // Note you have to *return* the promise from your lifecycle method
    componentWillMount() {
    return new Promise(function(resolve) {
    setTimeout(resolve, 100);
    });
    }
    }

    it('waits for the mount', async () => {
    const wrapper = await willMount(<MyComponent ... />);
    });