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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分