mercredi 19 février 2020

How to fire a click event on a child component with Jest and react-testing-library

I have been trying to write a test that will ensure that when a marker is clicked (from leaflet) further details will be displayed to the user. The Marker component is a child of the Map component. To start I am just wanting to see if the onClick function is called once when the marker is clicked.

The Map component returns the following structure

return(
  <LeafletMap>
    <Marker data-testid='marker' onClick={someFunc}/>
    <TileLayer/>
    <Popup/>
  </LeafletMap>
)

In my test I attempt to render the Map component and find the marker via a data-testid:

const handleParcelClick = jest.fn()
it('get parcel details upon clicking the marker', () => {
    const {getByTestId}= render(<Map lat={someNumber} lng={someNumber} zoom={14} parcels={fakeParcels} activeParcel={fakeDetails} onParcelClick={handleParcelClick} />) 
    const marker = getByTestId('marker')
    fireEvent.click(marker)
    expect(handleParcelClick).toBeCalledTimes(1)
});

When attempting to run I get the following error:

      at getElementError (node_modules/@testing-library/dom/dist/query-helpers.js:22:10)
      at args (node_modules/@testing-library/dom/dist/query-helpers.js:76:13)
      at getByTestId (node_modules/@testing-library/dom/dist/query-helpers.js:59:17)
      at Object.<anonymous>.it (src/ParcelDetails.test.tsx:58:20)

I have attempted using enzyme as well with no success. The data-testid in the actual code is unique for each marker, called marker above for simplicity. Am I going about this wrong? Should I be testing the Marker separately from the Map component?

Aucun commentaire:

Enregistrer un commentaire