QUnit with Ajax, QUnit passes the failing tests

房东的猫 提交于 2019-12-03 03:07:54
azamsharp

Starting and stopping using the QUnit library seems to be working!

// test to check if the persons are returned!
test("getPersons", function() {
  stop();
  getPersons(function(response) {
    persons = $.evalJSON(response.d);
    equals(persons[0].FirstName, "Mohammad");
    start();
  });
});

The real problem here isn't needing to call the start() and stop() methods - in fact you could get into trouble using that approach if you are not careful in calling stop() again at the end of your callback if you have additional .ajax() methods. Which then means you find yourself in some snarled mess of having to keep track if all the callbacks have been fired to know if you still need to call stop() again.

The root of the problem involves the default behavior of asynchronous requests - and the simple solution is to make the .ajax() request happen synchronously by setting the async property to false:

test("synchronous test", function() {
  $.ajax({
    url:'Sample.asmx/Service',
    async:false,
    success: function(d,s,x) { ok(true, "Called synchronously"); }
  });
});

Even still, the best approach is to allow the asynchronous behavior and use the right test method invocation: asyncTest(). According to the docs "Asynchronous tests are queued and run one after the other. Equivalent to calling a normal test() and immediately calling stop()."

asyncTest("a test", function() {
  $.ajax({
    url: 'Sample.asmx/Service',
    success: function(d,s,x) {
      ok(true, "asynchronous PASS!");
      start();
    }
  });
});

There a lot of qunit test in my project. like:

    module("comment");
    asyncTest("comment1", function() {
      expect(6);
      $.ajax({
        url: 'http://xxx.com/comment',
        dataType: "json",
        type: "GET",
        timeout: 1000
      }).done(function(data) {
        ok(true, "loaded");
        ok(data.data.length>1, "array size");
        ok(data.total, "attr total");
        var c = data.data[0];
        ok(c.id, "attr c.id");
        ok(c.user_id, "attr c.user_id");
        ok(c.type == 4, "attr c.type equal 4");
      }).fail(function(x, text, thrown) {
        ok(false, "ajax failed: " + text);
      }).always(function(){
        start();
      });
    });

ive done some qunit testing with ajax. its not pretty. the best thing i could come with is stopping the test when ajax is fired, and starting it again in the success callback. (using start() and stop()) methods. This meant one ajax request at a time, but i could live with that. Good luck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!