vendredi 17 juillet 2020

Sending value with fireEvent

I'm using the fireEvent from @testing-library/react. I declared a react component as follows:

const CustomParamTest = () => {
  onButtonClick(customParam) {
    console.log(customParam);
  }

  return (
    <>
      <button 
        data-testid="custom-param-button" 
        onClick={(customParam) => onButtonClick(customParam) }
      >
        Custom param
      </button>
    </>
  );
}

I have this test:

describe('basic test', () => {
  test('items should be empty', () => {
    const { getByTestId } = render(<CustomParamTest />);

    const customButton = getByTestId('custom-param-button');
    fireEvent.click(customButton);
  });
});

What I want to achive is to send a custom parameter with the click event, something like this:

fireEvent.click(customButton, myCustomParameter);

I want to access the myCustomParameter inside my onButtonClick function. I could make it work as follow but I want a better solution:

I created a custom click event like this:

const customEvent = createEvent.click(customButton, { button: 2 });
customEvent.myCustomProp = 'customValue';
fireEvent.click(customButton, customEvent);

And in my component I can access this value like this:

onClick={(e) => console.log(e.nativeEvent.myCustomProp)}

I feel like there should be a better way to do this.

Aucun commentaire:

Enregistrer un commentaire