Question

Is it possible to specify the circumstances the asyn callback should be called in intern? Let's say we have a test testing a method which performs several XHR Requests in a row. Specificaly, I'm trying to test my implementation of callback provided for Strophe.connect. It works that way it sends several XHR Requests to the server, which handle the initial XMPP (BOSH) handshake.

Is it possible to test that in 5 seconds the callback is called with status code 5 (Connected)? The problem is the callback is triggered more than once and I need to wait for the right status code, throw away the others.

var dfd = this.async(5000);

conn.connection.connect("jid", "pass", dfd.callback(function(status) {
    if(status === 5) {
        expect(status).to.have(something);
    } else {
        // here, I need to say intern to
        // do nothing, just let the callback 
        // to be triggered once more
    }
    return true;
}));
Was it helpful?

Solution

Because your callback will get called more than once, I'd suggest explicitly resolving the deferred rather than wrapping the callback with dfd.callback. Try something like this:

var dfd = this.async(5000);

conn.connection.connect('jid', 'pass', dfd.rejectOnError(function (status) {
    if (status !== 5) {
        return;
    }

    // do any assertions here

    // explicitly resolve the test since it was successful to this point
    dfd.resolve();
}));

First, you'll notice we wrap the callback with dfd.rejectOnError. This convenience method will reject the deferred if any Error is thrown during any execution of your callback function. Next, we got rid of the dfd.callback, as this will attempt to resolve the deferred if the wrapped callback executes without throwing an Error. Because your callback will be called multiple times, this won't work. By explicitly resolving the deferred only when your criteria is met (status !== 5 and any assertions pass) your callback can execute any number of times as long as the deferred resolves within five seconds.

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