How to test if element is not clickable in react-testing-library
Asked Answered
T

2

8

I have an element with an onClick handler which may be disabled by adding pointer-events: none to parent (parent disables children click). Now I want to test that my child is not clickable, how can I do this? Using userEvent.click throws error:

Error: Unable to perform pointer interaction as the element has `pointer-events: none`:

But this is exactly what I am trying to test...

Transfix answered 10/7, 2023 at 11:26 Comment(0)
G
14

You can use the pointerEventsCheck option of userEvent.click, which allows you to control how often the pointer events check is performed.

For example:

import { render, screen } from "@testing-library/react";
import userEvent, {
  PointerEventsCheckLevel,
} from "@testing-library/user-event";

test("child is not clickable when parent has pointer-events: none", () => {
  render(
    <div style={{ pointerEvents: "none" }}>
      <button onClick={() => console.log("clicked")}>Click me</button>
    </div>
  );
  const button = screen.getByRole("button", { name: /click me/i });

  userEvent.click(button, {
    pointerEventsCheck: PointerEventsCheckLevel.Never,
  });

  expect(console.log).not.toHaveBeenCalledWith("clicked");
});
Gardia answered 10/7, 2023 at 11:30 Comment(0)
F
-1

You could use expect().toThrow() as documented here.

Depending on your test setup, you could also pass your onClick a mocked function and assert that it is never called.

test('onClick is not called', () => {
    const mockFn = jest.fn();
    render(
        <Foo onClick={mockFn} />
    );

    // Add logic to prevent click and fire the event.

    expect(mockFn).not.toBeCalled();
});
Foldboat answered 10/7, 2023 at 11:49 Comment(1)
This would work but would test implementation and not behavior.Transfix

© 2022 - 2024 — McMap. All rights reserved.