简体   繁体   中英

What is the state-of-the-art approach to testing jQuery code?

I'm new to JavaScript. Imagine, I have following piece of code:

$(document).ready(function() {
  $('#nights').on('keyup', function() {
    var nights = +$(this).val();
    var dailyPrice = +$(this).closest(".tour").data("daily-price");
    $('#total').text(nights * dailyPrice);
    $('#nights-count').text($(this).val());
  });
});

How can I unit-test that the anonymous function

  1. retrieves the value of the current element,
  2. retrieves the data from +$(this).closest(".tour").data("daily-price") and
  3. then calls text(...) on $('#total') and $('#nights-count')

?

Note that I'm interested in unit tests (therefore creating a full-fledged a Selenium test suite, which types in something and then checks the value of the elements isn't suitable for me), which don't require me to add a new abstraction layer.

By abstraction layer I mean this: I could create class JQueryAbstraction and then 2 sub-classes - one, which calls real jQuery methods and another, which just counts the number of calls.

You can try introducing the popular Unit Testing lightweight frameworks like Jasmine, Mocha, QUnit

All these framework can co-exist with AngularJS, JQuery....etc

From your example, which you are trying with an anonymous function, you can convert that function to a non-anonymous function and pass it to the testing tool

to make sure the last line is reached I am introducing a simple global variable and assigning value to it, say done = true or done = false

Example:

var done = false;
var onReady = function() {
  $('#nights').on('keyup', function() {
    var nights = +$(this).val();
    var dailyPrice = +$(this).closest(".tour").data("daily-price");
    $('#total').text(nights * dailyPrice);
    $('#nights-count').text($(this).val());
  });
  done = true;
}

$(document).ready(onReady);

So now you can test your onReady code with unit testing as in Jasmine, you can comment the actual document ready

//$(document).ready(onReady);

And call the function via unit testing

describe("Document Ready Unit Testing", function() {
  it("call the function ", function() {
     done = false;
     onReady() ;
     expect(done).toEqual(true);//this will print the unit testing passed or failed
  });
});

But: If you are not interested in declaring the anonymous function separately then you can loop through the document object and get the ready event function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM