简体   繁体   中英

Not able to access DOM in useEffect hook when testing with Jest/Enzyme

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM