test-until
A utility that returns a promise that resolves when the passed function returns true. It works like Jasmine's waitsFor
, but Promise based.
Installation
Node.js:
npm install --save[-dev] test-until
Requirements
test-until requires a global variable Promise
which needs to be a A+ compliant promise implementation (such as is available by default in most modern browsers). If you need to polyfill Promise
for any reason (such as supporting IE 11), I recommend promise-polyfill.
Usage
var promise =
checkFunc
- A function that returns a truthy value once the promise should be resolved.until
will call this function repeatedly until it returnstrue
or the timeout elapses.message
(optional) - A message to help identify failing cases. For example, setting this to"value == 42"
will reject with an error of"timed out waiting until value == 42"
if it times out. Defaults to"something happens"
.timeout
(optional) - The number of milliseconds to wait before timing out and rejecting the promise. Defaults to1000
.
The three arguments can be supplied in any order depending on your preferences. For example, putting the message first can make the line read a little more like English:
Example with Test Framework
Here's an example using the Mocha testing framework.
var until =
test-until reads and works even better with access to async
/await
in your tests, allowing you to wait for multiple async conditions with no callbacks in a manner that reads much like English:
Advanced Usage
Setting the Default Timeout
Use until.setDefaultTimeout(ms)
to set the default timeout. You can easily set this to different values in different parts of your test suite by setting it in a beforeEach
// Set a global default timeout
Passing a falsy ms
resets to the default of 1000
.
Setting the Error Message from Inside the Check Function
The check function gets called with a special argument called setError
which allows the check function to specify an error to return if the until
call times out. This can be useful when integrating until
with other test assertions; for example, here's a snippet that will wait for val
to be 42
and will reject with an actual Chai assertion error if it fails.
Development
The test suite uses newer JavaScript features, so you need Node.js 6+ in order to run it. Run npm test
to run the suite.