enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.96k stars 2.01k forks source link

How to test the state values which are setting the state from local storage inside componentDidMount in enzyme using reactjs ? #2570

Closed yogendrakumar96 closed 1 year ago

yogendrakumar96 commented 1 year ago

How to test the values which are getting from local storage and that are setting inside componentDidMount in enzyme ? Thanks in advance

constructor(props){
super(props);
this.state = {
userProfile: [],
iconLetter: ""
};
};
componentDidMount() {
const resData = JSON.parse(localStorage.getItem('Ticket_Types);
if(resData) {
const stringWord = resData.userId.toString();
const firstLetter = stringWord.charAt(0);
const capitalLetter = firstLetter.toUpperCase();
this.setState({
userprofile: resData,
iconLetter: capitalLetter,
});
}
}

When I test like this it is giving me initial values.

let wrapper = shallow(<Component />);
expect(wrapper.update().state('iconLetter')).toBe("B");

Expected: "B", Received: "",

ljharb commented 1 year ago

You’re using shallow, so componentDidMount won’t fire because it’s not mounted.

yogendrakumar96 commented 1 year ago

But when I use mount is is saying "Cannot read properties of undefined (mount)" like this. Is there any way to test this. Can you please help me about this.

ljharb commented 1 year ago

Can you make a codesandbox using https://codesandbox.io/s/react-jest-and-enzyme-testing-9vo14 that reproduces the problem?

yogendrakumar96 commented 1 year ago

No I can't as data is coming from local storage, can you please suggest me a way to write the test cases for componentDidMount which is getting the data from local storage and setting state inside of the life cycle method

ljharb commented 1 year ago

Without a codesandbox it's not an easy ask, and unfortunately I don't have enough free time to provide consulting services. I'd suggest StackOverflow for that :-) Good luck!