Search code examples
javascriptjquerybackbone.jsjasminesinon

JasmineJS: alter DOM to create intended value


I'm writing unit test for a function that need to get value from DOM to process.

getProducts: function() {
  //Create query
  var queryData = {};
  var location = this.$('#location').val();
  var startDate = this.$('#arrival').datepicker('getDate');
  var endDate = this.$('#departure').datepicker('getDate');

  var locationType = this.$('#location option:selected').attr('data-location');
  if (locationType === 'hotel') {
    queryData.hotel = location;
  } else if (locationType === 'city') {
    queryData.city = location;
  }
  queryData.startDate = bookingApp.util.formatDateToData(startDate);
  queryData.endDate = bookingApp.util.formatDateToData(endDate);

  if ((!queryData.hotel && !queryData.city) || !queryData.startDate || !queryData.endDate) {
    return; // I need to get pass this
  }

  //Query to view
  if (this.listView !== null) {
    this.listView.cleanUp();
  }
  bookingApp.summary.reset();
  this.listView = new bookingApp.OrderListView({
    query: queryData
  });
  return false;
},

I need to get pass the first return statement, but I can't set value for queryData.city or queryData.hotel as they are local variables:

  if ((!queryData.hotel && !queryData.city) || !queryData.startDate || !queryData.endDate) {
    return; // I need to get pass this
  }

Are there any way to modify the value of this.$('#location').val() so it won't trigger the return?

I've tried:

view.$("#location").val("Newyork");

$("#location").val("Newyork");

But none of them working.

Here my spec:

var view;

beforeEach(function () {
  view = new bookingApp.OrderView();
});

it ('getProducts() should create new listView', function() {
  view.$("#location").val("Newyork");
  $("#arrival").val("2017-01-01");
  $("#departure").val("2017-01-03");
  view.getProducts();
  expect(view.listView instanceof bookingApp.OrderListView).toBe(true);
});

Solution

  • You need to mock the elements the view needs before you run the tests. Right now you trying to set values to element that does not exists.

    It should look something like:

    beforeEach(function () {
      $('div class="my-app"> /* all the required elements here */</div>').appendTo(document.body);
      view = new bookingApp.OrderView({
        el: '.my-app'
      });
    });
    

    Here document.body should be the document of test runner.