skip to Main Content

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…

2

Answers


  1. 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");
    });
    
    Login or Signup to reply.
  2. 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();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search