1

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

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

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

mockjax 文档

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

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

1 回答 1

2

您已经接近了,但是 Mockjax 模拟了 Ajax 请求的异步性质,这意味着您需要告诉 QUnit 这个测试是异步的以及它何时完成。此外,您实际上并没有进行任何 Ajax 调用,因此 Mock 处理程序永远不会受到影响。您需要将代码放入测试中以实际测试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 的单元测试指南异步文档

于 2017-07-31T14:36:28.350 回答