简体   繁体   English

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

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

I want to do unit testing on the Form component.我想对 Form 组件进行单元测试。 user is context data that is shared with all the children component. user是与所有子组件共享的上下文数据。

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

I have written a simple test case to test form component我写了一个简单的测试用例来测试表单组件

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

But the test case failed I think based on conditional rendering it doesn't go to test the Form component.但是测试用例失败了,我认为基于条件渲染它不会去测试 Form 组件。 How could we do the conditional rendering based on the context data?我们如何根据上下文数据进行条件渲染?

Try to add context provider at the top level:尝试在顶级添加上下文提供程序:

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);
});

I did this way and It worked.我这样做了,它奏效了。 @Ken Bekov Credits to you @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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM