1

In my useEffect hook I initialise a Leaflet map. It works all fine. But in the test it says "Map container not found.". To confirm I tried console.log(document.getElementById('mapid')). It finds the element when I run my app, but also not in the test. The DOM seems to be not yet rendered when I try to access it in useEffect.

This is my useEffect code:

 useEffect(() => {
    console.log(document.getElementById('mapid'))
    map.current = Leaflet.map('mapid').setView([46.378333, 13.836667], 12)
 }, [])

And this the according test:

describe('initialise map', () => {
    it('render map', () => {
        const MapComponent = () => <Provider store={store}><Map /></Provider>
        const component = mount(<MapComponent />)

        expect.some.really.unexpected.things
    })
})

How can I access the DOM in useEffect when testing?

Juuro
  • 1,487
  • 5
  • 16
  • 27
  • 2
    use a ref https://reactjs.org/docs/refs-and-the-dom.html – frozen Aug 09 '20 at 18:38
  • Does this answer your question? [Mocking \`document\` in jest](https://stackoverflow.com/questions/41098009/mocking-document-in-jest) – Aprillion Aug 09 '20 at 19:06
  • check out this articles that explains how to access dom elements inside `useEffect` hook, https://medium.com/@teh_builder/ref-objects-inside-useeffect-hooks-eb7c15198780 – Mu-Majid Aug 11 '20 at 18:58

2 Answers2

0

I ended up not checking the DOM but the Redux action I dispatch in the useEffect:

it('should initialise map without markers', () => {
    const MapComponent = () => <Provider store={store}><Map /></Provider>

    mount(<MapComponent />)

    const [{type: actionType}] = store.getActions()
    expect(actionType).toEqual('ADD_MAP')
})

I was not able to access the refs inside the test. I think this is because the actual Map component is wrapped inside of a Provider and therefore I can't access the refs of Map at the mounted component.

Juuro
  • 1,487
  • 5
  • 16
  • 27
0

You have to mock the useEffect implementation

describe('YOur test cases', () => {
  const useEffect = jest.spyOn(React, 'useEffect');
  const mockUseEffect = () => useEffect.mockImplementationOnce((f) => f());
  mockUseEffect();

  it('your 1st test case', () => {})

})
Ashish Singh Rawat
  • 1,419
  • 16
  • 30