React 测试库 - 使用 React.context 测试钩子

时间:2021-05-29 09:07:27

标签: reactjs react-hooks react-testing-library react-context react-hooks-testing-library

我对带有自定义钩子的 react-testing-library 有疑问

当我在自定义钩子中使用上下文时,我的测试似乎通过了,但是当我在钩子清理函数中更新上下文值但没有通过时。 那么有人可以解释为什么这是或不是测试自定义钩子的好方法吗?

提供者和钩子代码:

// component.tsx
import * as React from "react";

const CountContext = React.createContext({
  count: 0,
  setCount: (c: number) => {},
});

export const CountProvider = ({ children }) => {
  const [count, setCount] = React.useState(0);
  const value = { count, setCount };
  return <CountContext.Provider value={value}>{children}</CountContext.Provider>;
};

export const useCount = () => {
  const { count, setCount } = React.useContext(Context);

  React.useEffect(() => {
    return () => setCount(50);
  }, []);

  return { count, setCount };
};

测试代码:

// component.spec.tsx
import * as React from "react";
import { act, render, screen } from "@testing-library/react";
import { CountProvider, useCount } from "./component";

describe("useCount", () => {
  it("should save count when unmount and restore count", () => {
    const Wrapper = ({ children }) => {
      return <ContextStateProvider>{children}</ContextStateProvider>;
    };

    const Component = () => {
      const { count, setCount } = useCount();
      return (
        <div>
          <div data-testid="foo">{count}</div>
        </div>
      );
    };

    const { unmount, rerender, getByTestId, getByText } = render(
      <Component />, { wrapper: Wrapper }
    );
    expect(getByTestId("foo").textContent).toBe("0");
    unmount();

    rerender(<Component />);
    // I Expected: "50" but Received: "0". but I dont understand why
    expect(getByTestId("foo").textContent).toBe("50");
  });
});

0 个答案:

没有答案
相关问题