简体   繁体   English

使用 Jest/Enzyme 进行测试时无法在 useEffect 挂钩中访问 DOM

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

In my useEffect hook I initialise a Leaflet map.在我的useEffect挂钩中,我初始化了一个 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')) .为了确认我尝试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 .当我尝试在useEffect中访问 DOM 时,它似乎尚未呈现。

This is my useEffect code:这是我的 useEffect 代码:

 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?测试时如何访问useEffect中的 DOM?

I ended up not checking the DOM but the Redux action I dispatch in the useEffect:我最终没有检查 DOM,而是检查了我在 useEffect 中调度的 Redux 操作:

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.我认为这是因为实际的Map组件包装在Provider内部,因此我无法在已安装的组件上访问Map的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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