Question

How do asynchronous tests work in Intern testing framework? I have tried to get them run exactly as in the example, but the async test passes immediately without waiting for the callback to be run.

it('should connect in 5 seconds', function () {
    var dfd = this.async(5000);
    conn.connect(credentials, dfd.callback(function(result) {
        expect(result).to.... something
    }));
}

The test passes immediately. What am I doing wrong?

Was it helpful?

Solution

dfd.callback doesn’t execute anything until it itself is executed. Keep in mind that it is designed for promise callbacks (i.e. the function passed to promise.then), not Node.js-style callbacks where the argument might be an error (i.e. function (error, result) {}). It will not check to see if an error is passed as an argument.

Without knowing what conn is, but seeing how you are passing dfd.callback as an argument to something that is not a promise, my suspicion is you are trying to use a Node.js-style callback and the call is erroring immediately. We may provide a convenience wrapper for these types of callbacks in the future to convert them to a promise interface, but until then, you probably just need to do something like this:

it('should connect in 5 seconds', function () {
    var dfd = this.async(5000);
    conn.connect(credentials, dfd.callback(function(error, result) {
        if (error) {
            throw error;
        }

        expect(result).to.... something
    }));
});

Otherwise, without knowing what conn is and seeing what your actual assertion is, it’s too hard to say what the issue is here. So long as nothing inside the callback throws an error, the test will be considered successful.

Edit: So based on your comments above it sounds like your callback is an event listener called multiple times with different information. In this case, what you could do is something like this:

it('should connect in 5 seconds', function () {
    var dfd = this.async(5000);
    conn.connect(credentials, dfd.rejectOnError(function (result) {
        if (result !== 'what I want') {
            return;
        }

        expect(result).to.... something
        // all other tests…

        // nothing threw an error, so it is a successful test
        dfd.resolve();
    }));
});

dfd.rejectOnError works just like dfd.callback except it does not automatically resolve the promise; you do that yourself at the end.

OTHER TIPS

Your structure is okay. dfd sets a timeout of 5 seconds for the test to succeed, then immediately tries conn.connect(), which is not part of the intern framework. If you are trying a simple XHR request, try the getUrlCallback function instead.

They have a pretty cool list of tests at this url: https://github.com/theintern/intern/wiki/Writing-Tests . Look for the two async examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top