如何对jQuery Promises进行单元测试?

时间:2014-09-02 14:53:54

标签: jquery ajax unit-testing promise

我有以下四个函数,当使用参数进行promise解析时,将调用two(),three()和four()。让我再解释一下。

当我调用函数one()时,我传递默认参数值,但函数two()将在函数one()中使用promise的解析值调用。函数two(),three()和four()函数遵循类似的逻辑。

  function one(arg) {

  var deferred = $.Deferred(); // Don't worry yet what this is until after you understand the flow

  console.log("Starting one's ajax with arg: " + arg);
  $.ajax({
      url: '/',
      success: function() {

          // Here's where you want to call the next function in the
          // list if there is one. To do it, call deferred.resolve()
          console.log('Finished with one. Ready to call next.');
          deferred.resolve("This is one's result");

      }

  });

  // The deferred object has a "promise" member, which has a "then" function
  return deferred.promise();
}

function two(arg) {
  var deferred = $.Deferred();
  console.log("Starting two's ajax with arg: " + arg);
  $.ajax({
      url: '/',
      success: function() {

          // Again, this is where you want to call the next function
          // in the list if there is one.
          console.log('Finished with two. Ready to call next.');
          deferred.resolve("This is two's result");

      }

  });
  // The deferred object has a "promise" member, which has a "then" function
  return deferred.promise();
}

function three(arg) {
  var deferred = $.Deferred();
  console.log("Starting three's ajax with arg: " + arg);
  $.ajax({
      url: '/',
      success: function() {

          // Again, this is where you want to call the next function
          // in the list if there is one.
          console.log('Finished with three. Ready to call next if there is one.');
          deferred.resolve("This is three's result");

      }

  });
  // The deferred object has a "promise" member, which has a "then" function
  return deferred.promise();
}

function four(arg) {
  console.log("Starting four with arg: " + arg);
  console.log("Finished synchronous four");
}

// Test it out. Call the first. Pass the functions (without calling them, so no parentheses) 
// into the "then" calls.

one("arg given to one")
  .then(two)
  .then(three)
  .then(four);

2 个答案:

答案 0 :(得分:1)

目前,您的测试太多了。你真的想测试你的浏览器能够做AJAX吗?为什么?

第一步是提取函数,以便在单元测试中调用/链接它们。这样,您可以在单元测试中创建自己的promise,为它们提供函数并同步执行它们。

答案 1 :(得分:0)

在考虑了@Aaron的建议之后,我尝试了以下单元测试代码,以获得单个函数的成功方案,例如,函数1。

describe('Test example-1', function () {

  it('should check promise resolved with a custom message', function () {
     spyOn($, 'ajax').andCallFake(function (req) {
        var d = $.Deferred();
        d.resolve("I am done");
        return d.promise();
     });

     var expectedPromise = one();
     var result = "I am done";

     expectedPromise.then(function(response) {
       expect(response).toEqual(result);
     });
 });
});

我已经在我的github回购中推动了成功和失败的例子:

https://github.com/pulakb/UnitTesting-Promises/tree/master/Jasmine/jQuery