在 QUnit 中使用 Mockjax?

Using Mockjax in QUnit?

我在 Mockjax 文档中看到了这个例子:

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

但我不确定我应该如何将它与 QUnit 测试方法一起使用。 有任何想法吗?

mockjax docs

我试过了,但它说它至少需要一个断言,就好像它根本没有运行,断言行:

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?"
        }
    });
});

你很接近,但 Mockjax 模拟了 Ajax 请求的异步性质,这意味着你需要 tell QUnit that this test is asynchronous 以及它何时完成。此外,您实际上并没有进行任何 Ajax 调用,因此 Mock 处理程序永远不会被命中。您需要将代码放入测试中以实际 test ajax 调用(从而命中上面的模拟处理程序):

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.
        }
    });
});

我鼓励您阅读 QUnit's guide to unit testing, and the async documentation