代码之家  ›  专栏  ›  技术社区  ›  Carl Brubaker

qunit测试ajax成功函数

  •  1
  • Carl Brubaker  · 技术社区  · 6 年前

    我知道已经有很多关于这个的文章了,但是我在基线上并没有那么擅长于JavaScript,而且大多数应该有意义的文章都使用了一个让我困惑的旧语法。

    以下是我想要工作的功能:

    function getUpdateForm() {
      $.ajax({
        url: 'test_response.html',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
          $("#Form_div").html(data);
        },
      });
    };
    

    这是我的回复文件:

    <html>
      <head>
        <title>Test Response</title>
      </head>
      <body>
        <h1>Test Page</h1>
      </body>
    </html>
    

    这是我的质量测试:

    QUnit.test('getUpdateForm ajax request', function(assert) {
    
      $.ajax = function(request) {
        assert.equal(
          request.url,
          'test_response.html',
          'request url is correct'
        );
        assert.equal(request.type, 'GET',
          'request type is correct'
        );
        assert.equal(request.dataType, 'json',
          'request dataType is correct'
        );
      };
    
      getUpdateForm();
    
      setTimeout(function() {
        assert.equal($("#Form_div").html(), '',// not exactly sure what to put
          'Received correct html in response'
        );
        assert.async();
      }, 1000);
    });
    

    目前它甚至没有尝试运行 assert.equal setTimeout 功能。

    请尽可能多地提供细节,我可能会有很多问题。首先,测试是如何从 $.ajax = function(request) ?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Jordan Kasper    6 年前

    我知道你想做什么…但是有一个 tool to mock out Ajax requests 就为了这个目的!(我是它的维护者,但仍然…)

    基本上,在你的测试(或 beforeEach hook )您可以根据实际的Ajax调用创建一个模拟,然后进行代码测试。

    首先,我将在源代码函数中添加回调,这样我们就可以知道在测试中何时完成Ajax调用:

    function getUpdateForm(doneFunction) {
      $.ajax({
        url: 'test_response.html',
        type: 'GET',
        dataType: 'json',
        success: function(data) {
          $("#Form_div").html(data);
        },
        complete: doneFunction   // <-- this is new!
      });
    };
    

    现在用一个模拟设置测试,并执行断言…

    QUnit.test('getUpdateForm ajax request', function(assert) {
      let done = assert.async(); // set up an async test
    
      $.mockjax({
        url: "test_response.html",
        responseText: "<h1>Test Page</h1>"
      });
    
      getUpdateForm(function() {  // this is our callback function
        // now do your assertions on the content in the form div...
        assert.equal($("#Form_div h1").text(), 'Test Page', 'Received correct title in html response');
    
        done(); // then tell QUnit you are done testing.
      });
    });
    

    不要忘记包含mockjax JS文件 除了 Qunit JS文件!

    推荐文章