单位测试在回调中调用SetState时未更新状态
我正在测试一个简单的模态组件,当您单击按钮打开按钮时,请发送一个请求,其中有两个回调(成功,错误)。当成功回调称为3个状态时:
function sucessGet(data) {
console.log('sucessGet');
setIsLoaded(true);
setBody(true);
setVisible(true);
}
我要测试的唯一状态是可见
我将作为模式的道具发送的位置。
在我的测试中:
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'));
});
它调用onclick
函数:
onClick={() => {
reported ? '' : GetFraud();
}}
呼叫get froud
:
function GetFraud() {
console.log('getfraud');
setIsLoaded(false);
TransactionalAnalysisStore.GetFraudReport(eventId, sucessGet, errorGet);
}
并且完成所有完成的日志时,我的日志就是这样:
LOG: 'visible', false
LOG: 'visible', false
LOG: 'Before Props', false
LOG: 'getfraud'
LOG: 'visible', false
LOG: 'After Props', false
LOG: 'sucessGet'
success
is打电话给我的状态
(可见)没有更新,显然未能通过测试。
谁能给人希望,告诉我为什么这不会更新州?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的状态不会更新,因为Usestate Hooks的效果不佳。
意味着更新需要花费一些时间,使用异步等待它,希望它能起作用。
BEASR更新useeffect()挂钩中状态的方法,只需在Usefect上更新您的状态即可。
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.