Last active
September 10, 2017 20:50
-
-
Save tiagoengel/46076deca32d2b38831456ebfbb0319e to your computer and use it in GitHub Desktop.
small helper to facilitate tests with async code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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