Created
September 4, 2018 01:43
-
-
Save AndrewRayCode/7221fa4b80d0092fac759be9fc1cf44c to your computer and use it in GitHub Desktop.
Jest / sinon async componentWillMount test utility function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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