-1

I am creating a test case using JEST and RTL where I have to perform some action on button click event but I'm not able to fire a click event on that button.

My component looks like:-

const CustomButton = () => {
    return (
        <div data-testId="main">
          <div className="buttonContainer">
            // I can't put data-testId here as I'm in a situation where I don't have access to this button.
            <button className="button"> Button </button>
          </div>
        </div>
    )
}

My test case:-

it('should do some thing when button is clicked', () => {
    render(
      <CustomButtom />
    )
    // I tried accessing the button directly too
    fireEvent.click(
      screen
        .getByTestId('main')
        .querySelector('buttonContainer')
        ?.querySelector('button') as Element
    )
    // check something
  })

The error I'm getting-

Unable to fire a "click" event - please provide a DOM element.

Ankit Jaishwal
  • 496
  • 1
  • 9
  • 21
  • You can use getByRole('button') to get the button from your DOM. – Nayan shah Apr 03 '23 at 10:56
  • @Nayanshah TestingLibraryElementError: Unable to find an accessible element with the role "button" – Ankit Jaishwal Apr 03 '23 at 11:04
  • You have a couple of typos in your test—`.querySelector('buttonContainer')` instead of ".buttonContainer" (you want to querySelector on the class), and you are rendering `` instead of "CustomButto**n**" (unless it was imported like that, to be honest that could be a typo on the import). However, aside from that, if `screen.getByRole('button')` still doesn't return anything, then there is some other problem, because that would work with the JSX given. I would make sure that the element is mounted properly and you are getting the expected HTML in your test. – M. Desjardins Apr 03 '23 at 17:30

1 Answers1

0

If the Button text will not get changed. You can directly use

const button = screen.getByText('Button');

  fireEvent.click(button);

Or if you prefer using the query selector, you can use it like:

const button = screen
    .getByTestId('main')
    .querySelector('.buttonContainer button');

  fireEvent.click(button);
Arrow
  • 532
  • 5
  • 18
  • using getByText :- TestingLibraryElementError: Unable to find an element with the text: Filter. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. The querySelector one is giving the same error which I mentioned in the question – Ankit Jaishwal Apr 03 '23 at 11:03