PrimeReact Unit Test Issues

UI Components for React
Post Reply
chris-clark-rv
Posts: 2
Joined: 09 Jan 2023, 19:14

02 Feb 2023, 00:47

We're in the process of integrating PrimeReact into our application and are running into a few issues with our unit tests using react-testing-library and jest.

For example, I am trying to write a test to replicate a user clicking a ToggleButton.
We are normally wrapping the PrimeReact components in our own, but for the purposes of this post and to remove any possible fault on our side, I'm directly importing the PrimeReact component

Code: Select all

import { render, screen, prettyDOM } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import '@testing-library/jest-dom'
import { ToggleButton, ToggleButtonProps } from 'primereact/togglebutton'

describe('ToggleButton', () => {
  const setup = (props?: ToggleButtonProps) => {
    render(<ToggleButton data-testid="toggleButton" {...props} />)
  }
  it('clicks ToggleButton', async () => {
    setup()

    const ToggleButton = screen.getByTestId('toggleButton')

    console.log('before', prettyDOM(ToggleButton))
    await userEvent.click(ToggleButton)
    console.log('after', prettyDOM(ToggleButton))

    expect(ToggleButton).toHaveTextContent('Yes')
  })
})
The outcome of this test is:

Code: Select all

Expected element to have text content:
      Yes
    Received:
      No
Likewise, the output of the `console.log` statements shows the "before" and "after" instances to be the exact same. No text change, no aria-pressed change, etc.

Why is the userEvent click not triggering the click event on the PrimeReact ToggleButton component?
Can PrimeReact components not be tested in this way?
I've tried this same test approach with a standard HTML button and it works as expected.

Any help would be greatly appreciated!

Cheers,
-Chris

Melloware
Posts: 3717
Joined: 22 Apr 2013, 15:48

06 Feb 2023, 19:38

Here is my test for PrimeReact button. Make sure you are getting the "clickable" value element and not just clicking on the ToggleButton itself.

Code: Select all

test('when button is clicked ensure onClick is fired', async () => {
        // Arrange
        const clickOn = jest.fn();
        const { container } = render(<Button onClick={clickOn} />);
        const button = container.getElementsByClassName('p-button')[0];

        // Act
        await userEvent.click(button);

        // Assert
        expect(button).toBeEnabled();
        expect(clickOn).toHaveBeenCalledTimes(1);
    });
PrimeFaces Developer | PrimeFaces Extensions Developer
GitHub Profile: https://github.com/melloware
PrimeFaces Elite 13.0.0 / PF Extensions 13.0.0
PrimeReact 9.6.1

Post Reply

Return to “PrimeReact”

  • Information
  • Who is online

    Users browsing this forum: No registered users and 10 guests