Chapter 4. Asynchronous Testing – AJAX

Inevitably, there comes a time in every JavaScript application when asynchronous code needs to be tested.

Asynchronous means that you cannot deal with it in a linear fashion—a function might return immediately after its execution, but the result will come later, usually through a callback.

This is a very common pattern while dealing with AJAX requests, for example, through jQuery:

$.ajax('http://localhost/data.json', {
  success: function (data) {
    // handle the result
  }
});

In this chapter, we are going to learn the different ways Jasmine allows us to write tests for asynchronous code.

Acceptance criterion

To demonstrate Jasmine support of asynchronous testing, we are going to implement the following acceptance criterion:

Stock when fetched, should update its share price

Using the techniques we have showed you until now, you could write this acceptance criterion in StockSpec.js, inside the spec folder file, as follows:

describe("Stock", function() {
  var stock;
  var originalSharePrice = 0;

  beforeEach(function() {
    stock = new Stock({
      symbol: 'AOUE',
      sharePrice: originalSharePrice
    });
  });

  it("should have a share price", function() {
    expect(stock.sharePrice).toEqual(originalSharePrice);
  });

  describe("when fetched", function() {
    var fetched = false;
    beforeEach(function() {
      stock.fetch();
    });

    it("should update its share price", function() {
      expect(stock.sharePrice).toEqual(20.18);
    });
  });
});

That would lead to the implementation of the fetch function from the Stock.js file inside the src folder, as follows:

Stock.prototype.fetch = function() {
  var that = this;
  var url = 'http://localhost:8000/stocks/'+that.symbol;

  $.getJSON(url, function (data) {
    that.sharePrice = data.sharePrice;
  });
};

The important part in the preceding code is the $.getJSON call, an AJAX request expecting a JSON response containing an updated share price, such as:

{
  "sharePrice": 20.18
}

By now, you can see that we are stuck; in order to run this spec, we will need a server running.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset