Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qunit error: assertion outside test context

I've searched all over and it appears this error is due to not using asyncTest properly. However, per the documentation, it appears that I am doing it correctly. I'm guessing I'm missing a small detail somewhere and need an extra pair of eyes...

I'm trying to test some code that makes an ajax request to get a page and then loads it in a lightbox. lightbox-content does not show up in the DOM until after the ajax call has completed and can be displayed. So, I can only check for it in my onComplete call back, which is where I have my test to see if it loaded it correctly.

Here is my code:

asyncTest('mytest', 1, function() {
    utils.lightbox.show('/login', {
        onComplete: function() {
            ok($('#lighbox-content').is(':visible'), 'Lightbox loaded the /login page.');
            start();
        }
    });
});

I get the error:

Uncaught Error: assertion outside test context, was at HTMLDivElement.window.utils

Can anyone see where I'm going wrong?

like image 437
intargc Avatar asked Jun 05 '13 20:06

intargc


1 Answers

I agree that your code matches the documentation as far as I can tell.

Update

Even though the documentation doesn't show it, I wonder if you must tell QUnit to stop at some point so it knows to wait after the test function returns. I would think that QUnit assumes this since it's an async test, but it's worth a shot.

asyncTest('mytest', 1, function() {
    stop();
    ...
});

I've been using Sinon.JS to avoid making the AJAX calls in the first place. This has three immediate benefits:

  1. I don't depend on a server to respond to the requests.
  2. I can specify different results for each test.
  3. The tests run much faster.

The mocking can be done at the XMLHttpRequest level or on the jQuery method and is quite easy. Here's an example from one of my tests:

module("geo", {
    setup: function () {
        this.server = sinon.fakeServer.create();
    },

    teardown: function () {
        this.server.restore();
    }
}

test("returns detected ZIP code", function () {
    this.server.respondWith("/geo/detect-zip-from-ip",
                            [ 200, { "Content-Type": "text/html" }, '90210' ]);
    geo.detectZip(function (zip) {
        assertThat(zip, is('90210'));
    });
    this.server.respond();
});
like image 174
David Harkness Avatar answered Sep 16 '22 23:09

David Harkness