React Context not getting cleared after running each test in Jest

62 views Asked by At

I have a component where we display a prompt to the user to enter their name. Once they enter their name and hit the 'Let's get started' button, the login container disappears. I have also put a check to ensure that we don't allow a blank string to be used as the name. The username is saved in a UserContext and is consumed by other components. I have written two tests in Jest to test the same.

Here's the first test:

test("login prompt should disappear after user enters valid name", () => {
  render(
    <RouterProvider router={router}>
      <UserContext.Provider value={{ userName: "" }}>
        <Body />
      </UserContext.Provider>
    </RouterProvider>
  );

  const nameInput = screen.getByTestId("user-input");
  const submitButton = screen.getByRole("button", {
    name: "Let's get started !",
  });
  fireEvent.change(nameInput, { target: { value: "Girik" } });
  fireEvent.click(submitButton);
  expect(screen.queryByTestId("login-container")).toBeNull();
});

Here's the second test:

test("login prompt should not disappear if user enters invalid name", () => {
  render(
    <RouterProvider router={router}>
      <UserContext.Provider value={{ userName: "" }}>
        <Body />
      </UserContext.Provider>
    </RouterProvider>
  );

  const nameInput = screen.getByTestId("user-input");
  const submitButton = screen.getByRole("button", {
    name: "Let's get started !",
  });
  fireEvent.change(nameInput, { target: { value: "" } });
  fireEvent.click(submitButton);
  expect(screen.queryByTestId("login-container")).toBeDefined();
});

These two tests are run in the order specified above, and the expectation is that since they are two independent tests, the value of the UserContext should be cleared before the second test runs. However, the second test fails, and on logging, the value of userName in second test is showing as 'Girik', which means that the user context wasn't cleared.

If the order of tests is reversed, both of them pass, since the userName is not set in the first test in that case.

Can anyone help why the user Context is not getting reset after running every test?

0

There are 0 answers