weixin_33713350 2017-07-31 14:22 采纳率: 0%
浏览 48

在QUnit中使用Mockjax?

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?"
        }
    });
});
  • 写回答

1条回答 默认 最新

  • weixin_33724059 2017-07-31 14:36
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵