Подтвердить что ты не робот

Как протестировать проделанную работу и пропустить Отложенный объект, используя жасмин

Вот код о запросе на отправку javascript (1).
Вот тест об издевательстве запроса ajax с использованием жасмина (2).

Я хотел бы высмеять поведение сервера. Любые идеи?
Подробнее см. Комментарий в (1) и (2).

P.S.:
Фактически в обоих случаях вызывается завершенный и отложенный объект fakeFunction.


(1)

submitForm: function () {
     // the server execute fail only if message.val() is empty
     // and I would like to mock this behaviour in (2)
     backendController.submitForm(message.val()).done(this.onSuccess).fail(this.onError);
},

backendController.submitForm = function (message) {
    return $.ajax({
        url: 'some url',
        type: 'POST',
        dataType: 'json',
        data: {
            message: message
        }
    }).done(function () {
        //some code;
    });
};

(2)

describe('When Submit button handler fired', function () {
    var submitFormSpy,
        fakeFunction = function () {
            this.done = function () {
                return this;
            };
            this.fail = function () {
                return this;
            };
            return this;
        };

    beforeEach(function () {
        submitFormSpy = spyOn(backendController, 'submitForm').andCallFake(fakeFunction);
    });

    describe('if the message is empty', function () {
        beforeEach(function () {
            this.view.$el.find('#message').text('');
            this.view.$el.find('form').submit();
        });
        it('backendController.submitForm and fail Deferred Object should be called', function () {
            expect(submitFormSpy).toHaveBeenCalled();
            // how should I test that fail Deferred Object is called?
        });
    });

    describe('if the message is not empty', function () {
        beforeEach(function () {
            this.view.$el.find('#message').text('some text');
            this.view.$el.find('form').submit();
        });
        it('backendController.submitForm should be called and the fail Deferred Object should be not called', function () {
            expect(submitFormSpy).toHaveBeenCalled();
            // how should I test that fail Deferred Object is not called?
        });
    });

});
4b9b3361

Ответ 1

Мы на самом деле столкнулись с одной и той же проблемой, пытаясь протестировать объекты с отсрочкой, которые представляют собой сценарии шаблонов AJAXed для шаблонов на лету. В нашем тестовом решении используется библиотека Jasmine-Ajax в сочетании с самой Жасминой.

Скорее всего, это будет примерно так:

describe('When Submit button handler fired', function () {
  jasmine.Ajax.useMock();

  describe('if the message is empty', function () {

    beforeEach(function() {
      spyOn(backendController, 'submitForm').andCallThrough();
      // replace with wherever your callbacks are defined
      spyOn(this, 'onSuccess');
      spyOn(this, 'onFailure');
      this.view.$el.find('#message').text('');
      this.view.$el.find('form').submit();
    });

    it('backendController.submitForm and fail Deferred Object should be called', function () {
      expect(backendController.submitForm).toHaveBeenCalledWith('');
      mostRecentAjaxRequest().response({
        status: 500, // or whatever response code you want
        responseText: ''
      });

      expect( this.onSuccess ).not.toHaveBeenCalled();
      expect( this.onFailure ).toHaveBeenCalled();
    });
});

Другое дело, если можно, попытайтесь разбить функциональность, чтобы вы не тестировали весь путь обратного вызова DOM-to-response в одном тесте. Если вы достаточно гранулированы, вы можете проверить асинхронные отложенные разрешения, используя сами отложенные объекты внутри своих тестов!

Ключ состоит в том, чтобы фактически использовать объекты Отложенные в самих тестах, так что область вызова expect все еще находится в функциональном блоке it.

describe('loadTemplate', function() {
  it('passes back the response text', function() {
    jasmine.Ajax.mock();
    loadTemplate('template-request').done(function(response) {
      expect(response).toBe('foobar');
    });
    mostRecentAjaxRequest().response({ status:200, responseText:'foobar' });
  });
});

Ответ 2

Вот как мне это удалось.

По существу объект $.ajax возвращает объект Deferred, поэтому вы можете заглядывать в $.ajax и возвращать Deferred, а затем запускать его вручную для запуска кода .done() в вашем JavaScript

код

Index.prototype.sendPositions = function() {
  var me = this;
  $.ajax({
    ...
  }).done(function(data, textStatus, jqXHR) {
    me.reload();
  }).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(errorThrown);
  });
};

Тест

it("should reload the page after a successful ajax call", function(){
  var deferred = new jQuery.Deferred();
  spyOn($, 'ajax').andReturn(deferred);
  spyOn(indexPage, 'reload');
  indexPage.sendPositions();
  deferred.resolve('test');
  expect(indexPage.reload).toHaveBeenCalled();
});

Ответ 3

Было бы намного легче проверить, есть ли у вас var с объектом обещания запроса ajax. В этом случае вы можете сделать:

 it('should do an async thing', function() {     
   var mutex = 1;
   var promF = jasmine.createSpy('prF');

   runs( function() {
     var promise1 = $.ajax();
     promise1.always(function(){
       mutex--;
     });
     promise1.fail(function(){
       promF();
     });
   });

   waitsFor(function(){
     return !mutex;
   }, 'Fetch should end', 10000);

   runs( function() {
      expect(promF).toHaveBeenCalled();
   });
 });

Ниже я отправляю непроверенный код, который может вам подойдет. Я полагаю, что вызов ajax инициализирован из класса .submit()? Возможно, вы должны инициализировать запрос ajax из блока run(), а не из beforeEach(), но вы должны попробовать, какой из них работает.

describe('When Submit button handler fired and city is defined', function () {
    var ajaxRequestSpy,
        failSpy, successSpy, alwaysSpy,
        mutex;
    beforeEach(function () {
        ajaxRequestSpy = spyOn(backendController, 'ajaxRequest').andCallThrough();
        failSpy = spyOn(ajaxRequestSpy(), 'fail').andCallThrough()
        successSpy = spyOn(ajaxRequestSpy(), 'success').andCallThrough();
        mutex = 1; // num of expected ajax queries
        alwaysSpy =  spyOn(ajaxRequestSpy(), 'always').andCallFake(function() {
             mutex--;
        });
        this.view = new MyView({
            el: $('<div><form>' +
                '<input type="submit" value="Submit" />' +
                '<input type="text" name="city">' +
                '</form></div>')
        });
        this.view.$el.find('form').submit();
    });
    it('backendController.ajaxRequest should be called', function () {
        runs( function() {
            // maybe init ajax here ?   
        });

        waitsFor( function() {
            return !mutex;
        }, 'ajax request should happen', 5000);

        runs( function() {
            expect(ajaxRequestSpy).toHaveBeenCalled(); // true
            expect(failSpy).toHaveBeenCalled(); // Error: Expected spy fail 
                                            // to have been called.
        });

    });
});

Но я не уверен, что строка

failSpy = spyOn(ajaxRequestSpy(), 'fail').andCallThrough();

делает то, что вы хотите. Можно ли шпионить за другим шпионом? И если да, то почему вы называете шпиона? Возможно, вам стоит попробовать

failSpy = spyOn(ajaxRequestSpy, 'fail').andCallThrough();