mardi 18 août 2020

"Click" Event Not Firing for Jest

I'm writing some tests with jest and am not able to get a click event to fire.

Here's the first test, which works:

  it("should open drawer", () => {
    const { getByTestId } = render(<Header />);
    fireEvent.click(getByTestId("menuButton"));
    expect(getByTestId("drawer")).toBeVisible();
  });

The test successfully opens my "drawer" element with a click. The function works by removing the visibility: hidden style that's normally on this "drawer" element by default.

However, I'm having some trouble testing the "close" button, which adds that style back.

  it("should close drawer", () => {
    const { getByTestId } = render(<Header />);
    fireEvent.click(getByTestId("menuButton"));
    fireEvent.click(getByTestId("close"));
    expect(getByTestId("drawer")).not.toBeVisible(); // This doesn't work...
  });

The DOM (with screen.debug) doesn't seem to be picking up the second click. Logging the DOM shows that the styles not being applied. This happens despite the functionality working, for example withing Google Dev-Tools, using these functions:

// These both work....
$("button[data-testid='menuButton']").click()
$("button[data-testid='close']").click()

What's going wrong? Why is the second click event not firing?

Here's my full component:

import React, { useState } from "react";
import { Drawer, IconButton } from "@material-ui/core";
import Close from "@material-ui/icons/Close";
import Menu from "@material-ui/icons/Menu";
import history from "../../history";

import Links from "./links";

import "./style.scss";

const Header = React.memo(function Header(props) {
  const [mobileOpen, setMobileOpen] = useState(false);

  const handleGoHome = () => {
    history.push("/");
  };

  function handleDrawerToggle() {
    setMobileOpen(!mobileOpen);
  }

  return (
    <header className="header shadow">
      <nav>
        <IconButton
          data-testid="menuButton"
          onClick={handleDrawerToggle}
          className="menuButton pointer"
        >
          <Menu />
        </IconButton>
        <h1 onClick={handleGoHome} className="mainTitle pointer">
          Cloture
        </h1>
        <Drawer
          className="drawer"
          data-testid="drawer"
          anchor={"left"}
          open={mobileOpen}
          onClose={handleDrawerToggle}
        >
          <IconButton
            data-testid="close"
            className="close"
            onClick={handleDrawerToggle}
          >
            <Close />
          </IconButton>
          <Links
            setMobileOpen={setMobileOpen}
            links={[
              { label: "Calendar", link: "/calendar" },
              { label: "Senate", link: "/committees/senate" },
              { label: "House", link: "/committees/house" },
            ]}
          />
        </Drawer>
      </nav>
    </header>
  );
});

export default Header;

Aucun commentaire:

Enregistrer un commentaire