2014-09-02 2 views
0

У меня есть следующие четыре функции, в которых вызовы two(), three() и four() будут вызываться, когда с параметром появляется разрешение обещания. Позвольте мне объяснить, немного дальше.Как выполнить модульное тестирование jQuery Promises?

Когда я вызываю функцию one(), я передаю значение параметра по умолчанию, но функция function() будет вызываться с разрешенным значением обещания в функции one(). Аналогичная логика следует для функций 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); 
+0

У вас есть отложенные антипаттерны там, $ .ajax уже возвращает обещание - использовать его. –

+0

Кроме того, я могу понять ваш код просто отлично, но я понятия не имею, что вы спрашиваете здесь. –

+0

@BenjaminGruenbaum Я хотел бы написать единичные тестовые примеры вышеуказанного кода, чтобы позже я мог применять подобные идеи –

ответ

1

В настоящее время вы слишком много тестируете. Вы действительно хотите проверить, что ваш браузер способен делать AJAX? Зачем?

Первый шаг состоит в том, чтобы извлечь функции, чтобы вы могли вызывать/связывать их в своих модульных тестах. Таким образом, вы можете создавать свои собственные обещания в модульном тесте, кормить их функциями и выполнять их синхронно.

0

Принимая во внимание предложения @ Aaron, я попробовал следующий модульный тестовый код для успешного сценария одной функции, скажем, функции one.

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

Смежные вопросы