'Unit Tests not updating states when setState is called in a callback
I'm testing a simple modal component that when you click a button to open it, a request is sent where there are two callbacks (success, error). When the success callback is called 3 states are changed:
function sucessGet(data) {
console.log('sucessGet');
setIsLoaded(true);
setBody(true);
setVisible(true);
}
The only state that I'm testing is visible where I send as an prop to my modal.
In my test:
fit('Expect isOpen prop from AppModal to be true when successGet is called', () => {
component = mount(<ReportModal data={dataNotReported} viewIndex={1} />);
let AppModal = component.find('AppModal');
console.log('Before Props', AppModal.prop('isOpen'));
component.find('MdReportProblem').simulate('click');
console.log('After Props', AppModal.prop('isOpen'));
});
It calls the onClick function:
onClick={() => {
reported ? '' : GetFraud();
}}
That calls GetFraud:
function GetFraud() {
console.log('getfraud');
setIsLoaded(false);
TransactionalAnalysisStore.GetFraudReport(eventId, sucessGet, errorGet);
}
And when all that is done my logs are like this:
LOG: 'visible', false
LOG: 'visible', false
LOG: 'Before Props', false
LOG: 'getfraud'
LOG: 'visible', false
LOG: 'After Props', false
LOG: 'sucessGet'
After successGet is called, there is no update to my state(visible), obviously failing the test.
Can anyone give a light of hope and tell me why this is not updating the state?
Solution 1:[1]
Your state is not updating becasue of useState hooks works as a asyncronously. Means it takes take some time for update , use async await for it hope it will work. the beasr way to update state in useEffect() hook, just update your state on useEfect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HASEEB ALAM RAFIQ |
