Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Created September 4, 2018 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AndrewRayCode/7221fa4b80d0092fac759be9fc1cf44c to your computer and use it in GitHub Desktop.
Save AndrewRayCode/7221fa4b80d0092fac759be9fc1cf44c to your computer and use it in GitHub Desktop.
Jest / sinon async componentWillMount test utility function
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();
};
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 ... />);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment