Mattan Bitner
Mattan Bitner

Reputation: 1523

Qunit beforeEach, afterEach - async

Since start(), stop() will be removed in Qunit 2.0, what is the alternative for async setups and teardowns via the beforeEach, afterEach methods? For instance, if I want the beforeEach to wait for a promise to be finished?

Upvotes: 4

Views: 5007

Answers (3)

Alan Dong
Alan Dong

Reputation: 4095

Ember Qunit, has once exists beforeEach/setup, afterEach/teardown co-exist for a little while.

See PR: https://github.com/emberjs/ember-qunit/pull/125

Upvotes: 0

buer
buer

Reputation: 330

Seeing that nobody has answered the beforeEach/afterEach part: a test suite is supposed to run as soon as the page loads. When that is not immediately possible, then resort to configuring QUnit:

QUnit.config.autostart = false;

and continue with setting up your test suite (initializing tests, feeding them to QUnit, asynchronously waiting for some components to load, be it AJAX or anything else), your site, and finally, when it's ready, just run:

QUnit.start();

QUnit's docsite has it covered.

Upvotes: 0

Jordan Kasper
Jordan Kasper

Reputation: 13273

QUnit basically wants people to stop using the global methods (not just start() and stop(), but also test(), expect(), etc). So, as of version 1.16.0, you should always use either the global namespace (QUnit) or the assert API argument passed into the test() functions. This includes the new async control:

QUnit.test( "testing async action", function( assert ) {  // <-- note the `assert` argument here
    var done = assert.async();  // tell QUnit we're doing async actions and
                                // hold onto the function it returns for later

    setTimeout(function() {  // do some async stuff
        assert.ok( true, "This happened 100 ms later!" );

        done();  // using the function returned from `assert.async()` we 
                 // tell QUnit we're don with async actions
    }, 100);
});

If you are familiar with the old start() and stop() way of doing things, you should see that this is extremely similar, but more compartmentalized and extensible.

Because the async() method call is on the assert argument into the test, it cannot be used in the beforeEach() function. If you have an example of how you were doing that before, please post it and we can try to figure out how to git it into the new way.

UPDATE

My mistake previously, the assert object is being passed into the beforeEach and afterEach callbacks on modules, so you should be able to do the same logic that you would do for a test:

QUnit.module('set of tests', {
    beforeEach: function(assert) {
        var done = assert.async();
        doSomethingAsync(function() {
            done(); // tell QUnit you're good to go.
        });
    }
});

(tested in QUnit 1.17.1)

Upvotes: 9

Related Questions