mercredi 12 août 2020

Globals in enzyme/jest is a react node rather than a dom node

function App(){
  const ref=useRef()
  useEffect(()=>{
    console.log(ref.current)
    console.log(ref.current.offsetWidth)
  },[])
  return <div ref={ref}></div>
}

I got some code like about and try to test it out in jest, one base requirement is that ref.current.offsetWidth should be greater than 0

However, ref.current is something like this when I mount the component

HTMLDivElement {
  '__reactContainere$36yfa3ajf2y': FiberNode {
    tag: 3,
    key: null,
    elementType: null,
    type: null,
    stateNode: FiberRootNode {
      tag: 0,
      current: [Circular],
      containerInfo: [Circular],
      pendingChildren: null,
      pingCache: null,
      finishedExpirationTime: 0,
      finishedWork: null,
      timeoutHandle: -1,
      context: {},

I looks a lot like a react node rather than a dom node, thus the behaviour in jest do not match the real one.

Here is my code to mount

 mount(<App />, {attachTo:document.createElement('div')}) 

When I console.log document.createElement('div') directly I still something like this:

HTMLDivElement {
  '__reactContainere$36yfa3ajf2y': FiberNode {
    tag: 3,
    key: null,
    elementType: null,
    type: null,
    stateNode: FiberRootNode {
      tag: 0,
      current: [Circular],
      containerInfo: [Circular],
      pendingChildren: null,
      pingCache: null,
      finishedExpirationTime: 0,
      finishedWork: null,
      timeoutHandle: -1,
      context: {},
      pendingContext: null,
      hydrate: false,
      callbackNode: null,
      call

It seems that the document is provided as a jest global through jsdom, how come it is a react node rather than a dom node?

Aucun commentaire:

Enregistrer un commentaire