等待测试中的反应变量的正确方法是什么?

问题描述

给出反应性变量

export const isLoggedInVar: ReactiveVar<boolean> = cache.makeVar<boolean>(
  !!localStorage.getItem("apiToken")
);

注销钩子简化为:

function uselogout(): dispatch<SetStateAction<boolean>> {
  const client = useApolloClient();
  const [loggedOut,setlogout] = useState(false);

  useEffect(() => {
    const resetCache = async (): Promise<void> => {
      localStorage.clear(); // remove api token
      isLoggedInVar(false); // update reactive variable
      client.resetStore();
    };

    if (loggedOut) {
      resetCache();
    }
  },[loggedOut,client]);

  return setlogout;
}

还有一个调用该钩子的组件:

const ProfileHeader: React.FC = () => {
  const setlogout = uselogout();

  return isLoggedInVar() ? (
      <p>
        <Link to="/settings/">
          <span className="m-auto">Settings</span>
        </Link>

        <button
          type="button"
          data-testid="logout-button"
          onClick={(): void => setlogout(true)}
        >
          Log out
        </button>
      </p>
  ) : null;
};

当我为组件编写测试时,我被迫在测试中使用await waitFor(() => {});

describe("ProfileHeader",() => {
  it("should allow users to logout",async () => {
    isLoggedInVar(true);

    const { container,getByTestId,queryByTestId } = renderApollo(
      <MemoryRouter>
        <ProfileHeader />
      </MemoryRouter>
    );

    expect(isLoggedInVar()).toBeTruthy();
    expect(getByTestId("logout-button")).toBeTruthy();
    userEvent.click(getByTestId("logout-button"));

    waitForElementToBeRemoved(queryByTestId("logout-button"));
    expect(localStorage.getItem("apiToken")).toBeNull();

    // await new Promise((resolve) => setTimeout(resolve,0)); // works too
    await waitFor(() => {});
    expect(isLoggedInVar()).toBeFalsy();
  });
});

但是testing-library documentation mentions

使用空回调被认为是不好的做法,因为这会使测试更加脆弱。

我真的想做:

- await waitFor(() => {});
- expect(isLoggedInVar()).toBeFalsy();
+ await waitFor(() => expect(isLoggedInVar()).toBeFalsy());

但这给了我无数的错误

测试中对ProfileHeader的更新未包含在act(...)中。

我不理解。

我的测试等待反应变量更改的正确方法是什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)