react-testing-library: Using `await wait(...)` hangs jest test

  • react-testing-library version: 5.3.0
  • jest version: 23.6.0
  • react version: 16.7 alpha 2
  • node version: 11.0.0
  • npm (or yarn) version: 6.4.1

Relevant code or config:


const MockComponent = ({ callback }) => {
  const ref = React.useRef(null)

  return (
    <div ref={ref}>
      <h1>Some Header</h1>

      <div>
        <h6>Some Child Header</h6>
      </div>
    </div>
  )
}

describe('GoodTest', async () => {
  test('callback should be called when clicking on document', async () => {

    const callback = jest.fn()

    const { getByText, unmount } = render(<MockComponent callback={callback} />)

    await waitForElement(() => getByText(/Some Header/))

   // I never see 'good' in the console
   // the test never completes
    await wait(() => {
      expect(1).toEqual(1)
      console.log('good')
    })

  })
})

What you did:

I’m trying to test a component with a react hook that attaches a click listener on the document, but the listener is not applied by the time I am accessing it with the ‘waitForElement’ … So now, I’m using wait() to wait for something to appear, however, the test is never completing.

What happened:

My computer fan revs up like crazy, making me think it is stuck in an infinite loop.

Reproduction:

I don’t have a repo up yet, but I can set one up if that will help.

Something important to note was that I ran a single test with Jest doing jest "GoodTest" I am testing now to see if I get the same behaviour by running all tests.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 5
  • Comments: 15 (7 by maintainers)

Most upvoted comments

This probably has something to do with an issue that I saw with useEffect. I haven’t investigated it, but I’m pretty sure that there’s a bug in jsdom with useEffect where React’s scheduler schedules it for later, but that later never comes for some reason… I haven’t dug into it and don’t have time to now. I would love to know what’s going on though if you’re interested in doing some digging.

What I recommend doing instead is using flushEffects and keeping things synchronous. I actually talked about this a bit in my newsletter today if that interests you: https://kcd.im/news

I’m going to go ahead and leave this open because I think this would be a good problem to figure out, but I’m fairly confident that the solution will not be in this project, but in jsdom (note: the reason I think it’s a jsdom issue is because the problem does not surface when run in the browser).

I just had this issue, might have to do with unfinished tests, especially if you have conditionals in your code and you didn’t handle else case. not sure!