Skip to content

Instantly share code, notes, and snippets.

@tiagoengel
Last active September 10, 2017 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagoengel/46076deca32d2b38831456ebfbb0319e to your computer and use it in GitHub Desktop.
Save tiagoengel/46076deca32d2b38831456ebfbb0319e to your computer and use it in GitHub Desktop.
small helper to facilitate tests with async code
/**
* Small helper that keeps all running promises on a
* queue and allows a test to wait for all async code
* to finish before doing any assertions
*/
const NativePromise = window.Promise
let queue = []
class TestPromise extends NativePromise {
constructor(cb) {
super(cb)
queue.push(this)
}
}
/**
* Install test promises. Make it possible to
* wait for all promises by calling `flushPromiseQueue`
*/
export default function install() {
window.Promise = TestPromise
}
/**
* Clears the promise queue.
*
* @returns {Promise} a promise the resolves only when all promises are finished
*/
export function flushPromiseQueue() {
const all = NativePromise.all(queue)
queue = []
return all
}
/**
* Restore window.Promise to its initial value
*/
export function restore() {
queue = []
window.Promise = NativePromise
}
// now you need to install it in your a setup file somewhere
// e.g setup.js
// beforeEach(() => install())
// afterEach(() => restore())
// and use in a test
// import { flushPromiseQueue } from 'test/promises'
// ...
// flushPromiseQueue().then(() => {
// asserts here are guaranted to run after all promises are finished
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment