使用 Jest 和 Enzyme 测试基于 ContextAPI 数据的组件条件渲染

Test conditional rendering of components based on ContextAPI data using Jest and Enzyme

我想对表单组件进行单元测试。 user 是与所有子组件共享的上下文数据。

 const { user } = useContext(UserContextAPI);
 return (
  <> {!user ? (
        <>
          {navigation.push({
            pathname: "./Login",
            state: { editProduct: "edit" },
          })}
        </>
      ) : (
        <Form>.....</From>
      )
  }
 </>
);

我写了一个简单的测试用例来测试表单组件

 it("should contain From component", () => {
   let wrapper = mount(
      <BrowserRouter>
        <EditProduct.WrappedComponent />
      </BrowserRouter>
    );
    expect(wrapper.find("Form").exist()).toEqual(true);
  });

但是测试用例失败我认为基于条件渲染它不会去测试表单组件。我们如何根据上下文数据进行条件渲染?

尝试在顶层添加上下文提供程序:

it("should contain From component", () => {
    const UserContextAPI = React.createContext({});

    let wrapper = mount(
        <UserContextAPI.Provider value="{}">
            <BrowserRouter>
                <EditProduct.WrappedComponent />
            </BrowserRouter>
        </UserContextAPI.Provider>
    );
    expect(wrapper.find("Form").exist()).toEqual(true);
});

我这样做了并且成功了。 @Ken Bekov 感谢您

it("should contain From component", () => {
   const history = createBrowserHistory();
    const state = { pid: 1 };
    history.push("/EditProduct", state);
    wrapper = mount(
      <UserContextAPI.Provider value={{ user: 1 }}>
        <Router history={history}>
          <EditProduct.WrappedComponent />
        </Router>
      </UserContextAPI.Provider>
    );
    expect(wrapper.find("Form").exist()).toEqual(true);
});