简体   繁体   English

在QUnit中使用Mockjax吗?

[英]Using Mockjax in QUnit?

I see this example in Mockjax docs: 我在Mockjax文档中看到以下示例:

$.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. 但是我不确定如何将其与QUnit测试方法一起使用。 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?"
        }
    });
});

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. 您已经接近了,但是Mockjax模仿了Ajax请求的异步特性,这意味着您需要告诉QUnit此测试是异步的以及何时完成。 Additionally, you're not actually doing any Ajax calls, so the Mock handler would never get hit. 另外,您实际上并没有进行任何Ajax调用,因此Mock处理程序将永远不会受到攻击。 You would need to put code in your test to actually test the ajax call (thus hitting the mock handler you have above): 您将需要在测试中放入代码以实际测试 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.
        }
    });
});

I would encourage you to read QUnit's guide to unit testing , and the async documentation . 我鼓励您阅读QUnit的单元测试指南异步文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM