Skip to content

fireEvent.keyPress() is not working #1258

Closed as not planned
Closed as not planned
@ak-spotter

Description

@ak-spotter

I have a checkbox which I want to test using keyPress. The checkbox should be checked on pressing the Space key.
Here's my Component file-

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <input type="checkbox" data-testid="testing-it" />
    </div>
  );
}

And the test file-

import { fireEvent, render } from "@testing-library/react";
import "@testing-library/jest-dom";

import App from "./App";

describe("App", () => {
  it("should work as expected", async () => {
    const { getByTestId } = render(<App />);

    const testCheckBox = getByTestId("testing-it");
    expect(testCheckBox).not.toBeChecked();
    console.log("testCheckBox...", testCheckBox);

    fireEvent.focus(testCheckBox);
    fireEvent.keyPress(testCheckBox, {
      keyCode: 32,
      charCode: 32,
      key: " ",
      code: "Space"
    });

    expect(testCheckBox).toBeChecked(); // this fails
  });
});

The test fails at the second expect statement- expect(testCheckBox).toBeChecked(); However it should have passed as I focused the checkbox and pressed the Space key.

CodeSandbox link- https://codesandbox.io/s/cool-star-6k6ghp

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions