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

Viewed 455

I want to do unit testing on the Form component. user is context data that is shared with all the children component.

 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. How could we do the conditional rendering based on the context data?

2 Answers

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

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