'JavaScript wait for dynamic modules in Jest tests

Q: How can I wait for all my dynamic modules to be finished before my assertions in Jest ?

Scenario:

// normal code
export default {
  a() {
     import('b', () => {
        window.hello = 'there'
     })
  }
}
// test
import normalCode from 'normalCode'
it('should add to window', () => {
  normalCode.a()
  expect(window.hello).toBe('there')
})

The execution of the code above is:

  1. runs normalCode.a()
  2. runs expect(window.hello).toBe('there')
  3. import finished and is running window.hello = 'there'
  4. it fails because assertions were wrong at step 2, but they would pass after step 3.


Solution 1:[1]

I believe you'll want to return the import promise from function a.

// normal code
export default {
  a() {
     return import('b', () => {
        window.hello = 'there'
     })
  }
}

Then await it in your test.

// test
import normalCode from 'normalCode'
it('should add to window', async () => {
  await normalCode.a()
  expect(window.hello).toBe('there')
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alan Friedman