Intern Async

intern

// Intern - Asynchronous testing:

Asynchronous testing in Intern is based on promises.  We may either return a 
promise from a test function, or call this.async from within a test function 
to enable asynchronous testing.

If our test returns a promise (any object with a method named "then"), it is 
understood that our test is asynchronous.  Resolving the promise indicates a 
passing test, and rejecting the promise indicates a failed test.  The test will 
also fail if the promise is not fulfilled within the timeout of the test.  The 
default is 30 seconds.  Use this.timeout to change the timeout value.

The this.async method returns a Deferred object for asynchronous testing.  After 
calling this method, Intern will assume that our test is asynchronous, even if 
our test function does not return a promise.  If our test method does return a 
promise, the returned promise takes precedence over the promise generated by 
this.async.

The this.async method returns a Deferred object that can be used to resolve the 
test when it is finished.  In addition to the standard Deferred API, this 
Deferred object has two additional methods:

1. callback: This method is used to wrap a callback function and will resolve 
   the Deferred automatically when it is invoked, so long as the callback 
   function does not throw any error.  If the callback function throws an error, 
   the Deferred will be rejected with that error.
2. rejectOnError: This function works in the same way as the callback function, 
   except that it will only reject the Deferred when there is an error.  This is 
   useful when working with nested callbacks where only the innermost callback 
   should resolve the Deferred but a failure in any of the outer callbacks should 
   reject it.

The this.async method accept two optional parameters.  The first parameter, 
timeout, will set the timeout of our test in milliseconds.  If not provided, it 
defaults to 30 seconds.  The second parameter, numCallsUntilResolution, allows 
us to specify the number of times that the callback should be invoked before 
actually resolving the promise.  If not provided, this defaults to 1.  This 
parameter is useful in rare cases where we may have a callback that will be 
called several times and the test should be considered completely only on the 
last invocation.

A basic asynchronous test using this.async:

registerSuite({
  name: 'async demo',
  'async test': function() {
    var dfd = this.async(1000);
    request('http://example.com/test.json')
      .then(function() {
        dfd.callback(function(data) {
          assert.strictEqual(data, 'Hello world!');
        });
      }, function(){
        dfd.reject.bind(dfd);
      });
  }
});
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License