Search code examples
javascriptjqueryajaxqunitmockjax

Using Mockjax in QUnit?


I see this example in Mockjax docs:

$.mockjax({
  url: "/rest",
  data: function ( json ) {
    assert.deepEqual( JSON.parse(json), expected ); // QUnit example.
    return true;
  }
});

But I am not sure how should I use it with QUnit testing methods. Any ideas?

mockjax docs

I tried this but it says it expected at least one assertion, as if it doesn't run it at all, the assert line:

QUnit.test("mockjax test", function (assert) {
    $.mockjax({
        url: "/restful/fortune",
        data: function (json) {
            assert.deepEqual(JSON.parse(json), expected); // QUnit example.
            return true;
        },
        responseText: {
            status: "success",
            fortune: "Are you a mock turtle?"
        }
    });
});

Solution

  • You're close, but Mockjax emulates the async nature of Ajax requests which means you need to tell QUnit that this test is asynchronous and when it is complete. Additionally, you're not actually doing any Ajax calls, so the Mock handler would never get hit. You would need to put code in your test to actually test the ajax call (thus hitting the mock handler you have above):

    QUnit.test("mockjax test", function (assert) {
        // This is QUnit's callback for async testing
        let done = assert.async();
    
        // You also need to define the `expected` data
        let expected = { foo: "bar" };
    
        $.mockjax({
            url: "/restful/fortune",
            data: function (json) {
                assert.deepEqual(JSON.parse(json), expected); // QUnit example.
                return true;
            },
            responseText: {
                status: "success",
                fortune: "Are you a mock turtle?"
            }
        });
    
        // Now add the actual function call to your SOURCE code that you're testing...
        // Since I don't know your source code, I'll just put a jquery ajax call here
        $.ajax({
            url: "/restful/fortune",
            data: { foo: "bar" },
            complete: function() {
                done(); // now we tell QUnit that our test is complete.
            }
        });
    });
    

    I would encourage you to read QUnit's guide to unit testing, and the async documentation.