How to unit test React Component shouldComponentUpdate method

后端 未结 2 650
春和景丽
春和景丽 2021-02-18 16:04

I have a React Component that implements the shouldComponentUpdate method and I\'d like to unit test it. Ideally I could change some prop or state on the component in a unit tes

2条回答
  •  鱼传尺愫
    2021-02-18 16:41

    I would probably just call shouldComponentUpdate directly.

    Something like

    const comp = shallow()
    const shouldUpdate = comp.instance().shouldComponentUpdate(nextProps, nextState)
    expect(shouldUpdate).toBe(true/false)
    

    Trying to test by determining if the component actually rendered/didn't render is probably more trouble than it's worth; I'm not even sure how you would do that using enzyme. You can't really go off of the rendered output, since you would probably not return false from shouldComponentUpdate unless the rendered output was the same as before. So determining if a render occurred or not couldn't come from the output alone.

    Testing by calling it directly seems fine to me though. As long as you trust React is going to use your shouldComponentUpdate return value correctly (we have bigger problems if it doesn't), it's safe.

提交回复
热议问题