Want to mock componentDidMount or overwrite it in React? I prefer the following approach, but requires using ES6 classes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // component.jsx class Component extends React.Component { componentDidMount() { return this.setState({name: 'blabla'}); } render() { return (<h1>{this.state.name}</h1>); } } //component-spec.jsx describe('Component', () => { it('does stuff', () => { let ComponentTest = class extends Component { componentDidMount() { // your override here } }; let component = TestUtils.renderIntoDocument(<ComponentTest />); //expect(component...).toEqual(...) }); }); |
The point is to create an on demand ChildClass inheriting the OriginalClass, do whatever overrides and then TestUtils.renderIntoDocument(
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.