Ad
Jest/Enzyme | Test A Function Call In ComponentDidMount
What to do when you want to test that a function is been called, on componentDidMount()
React lifecycle Method. Basically the component code looks like this:
state = {
randomStateToPopulate: []
};
// Test componentDidMount
componentDidMount() {
this.randomFunction();
}
randomFunction= () => {
listRandomData().then(({ data }) => {
this.setState({ randomStateToPopulate: data });
});
};
So, how to you actually test this case?
Ad
Answer
This is the case scenario you want to test. If the componentDidMount is being called, check that it has been called only once, or as many times you want.
Your test. I have the explanation in comments below
// Inside your general `Describe`
let wrapper;
const props = {
// Your props goes here..
};
beforeEach(() => {
wrapper = shallow(<YourComponent {...props} />);
});
it('should check `componentDidMount()`', () => {
const instance = wrapper.instance(); // you assign your instance of the wrapper
jest.spyOn(instance, 'randomFunction'); // You spy on the randomFunction
instance.componentDidMount();
expect(instance.randomFunction).toHaveBeenCalledTimes(1); // You check if the condition you want to match is correct.
});
You can abstract, this case to do more complex things, but the basic gist of it is the above one. If you have a more detailed or better solution, please post it. Thanks!!
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad