Jestjs 在测试中等待反应变量的正确方法是什么?
给定一个反应变量Jestjs 在测试中等待反应变量的正确方法是什么?,jestjs,apollo-client,react-testing-library,reactive-variable,Jestjs,Apollo Client,React Testing Library,Reactive Variable,给定一个反应变量 export const isLoggedInVar:ReactiveVar=cache.makeVar( !!localStorage.getItem(“apiToken”) ); 注销挂钩简化为: 函数useLogout():分派{ const client=useAppolloClient(); const[loggedOut,setLogout]=使用状态(false); useffect(()=>{ const resetCache=async():Promise=
export const isLoggedInVar:ReactiveVar=cache.makeVar(
!!localStorage.getItem(“apiToken”)
);
注销挂钩简化为:
函数useLogout():分派{
const client=useAppolloClient();
const[loggedOut,setLogout]=使用状态(false);
useffect(()=>{
const resetCache=async():Promise=>{
localStorage.clear();//删除api标记
isLoggedInVar(false);//更新反应变量
client.resetStore();
};
if(loggedOut){
重置缓存();
}
},[loggedOut,客户];
返回设置注销;
}
以及一个调用钩子的组件:
const ProfileHeader:React.FC=()=>{
const setLogout=useLogout();
返回isLoggedInVar()(
设置
setLogout(真)}
>
注销
):null;
};
当我为组件编写测试时,我被迫使用wait-waitFor(()=>{})代码>在测试中
description(“ProfileHeader”,()=>{
它(“应该允许用户注销”,异步()=>{
isLoggedInVar(真);
const{container,getByTestId,queryByTestId}=renderApollo(
);
expect(isLoggedInVar()).toBeTruthy();
expect(getByTestId(“注销按钮”)).toBeTruthy();
点击(getByTestId(“注销按钮”);
waitForElementToBeRemoved(queryByTestId(“注销按钮”);
expect(localStorage.getItem(“apiToken”).toBeNull();
//等待新的承诺((resolve)=>setTimeout(resolve,0));//同样有效
等待等待(()=>{});
expect(isLoggedInVar()).toBeFalsy();
});
});
但是:
使用空回调被认为是不好的做法,因为它会使测试更加脆弱
我真的很想做:
-wait waitFor(()=>{});
-expect(isLoggedInVar()).toBeFalsy();
+wait waitFor(()=>expect(isLoggedInVar()).toBeFalsy());
但这给了我无数的错误
测试中对ProfileHeader的更新未包装在act(…)中
我不明白
我的测试等待反应变量改变的正确方法是什么