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://0.0.0.0/data.json', {
  success: function (data) {
    // handle the result
  }
});

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

"Stock when fetched, should update its share price."

By using the techniques we showed you so far, you could write this acceptance criterion in the spec/StockSpec.js file as follows:

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

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

That would lead to the implementation of the fetch function at the src/Stock.js file:

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

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

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

{
  "sharePrice": "23.67"
}

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

Setting up the Scenario

Since this book is all about JavaScript, we are going to create a very simple Node.js server to be used by the specs. Node.js is a platform that allows the development of network applications, such as web servers, using JavaScript.

In Chapter 6, Light Speed Unit Testing, we are going to see alternative solutions to test AJAX requests without the need of a server.

Installing Node.js

If you already have Node.js installed, you can skip to the next section.

There are installers available for Windows and Mac OS X:

  • Go to the Node.js website http://nodejs.org/
  • Click on the Install button
  • Once the download is completed, execute the installer and follow the steps

To check other installation methods and instructions on how to install on Linux distributions, check the official documentation at https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager.

Once you are done, you should have a node command available on your command line.

Coding the server

For the purpose of learning how to write asynchronous specs, we are going to create a server that returns some fake data. Create a new file in the project's root folder called server.js, and add its content:

var express = require('express'),
var app = express();

app.get('/stocks/:symbol', function (req, res) {
  res.setHeader('Content-Type', 'application/json'),
  res.send({ sharePrice: 20.18 });
});

app.use(express.static(__dirname));

app.listen(8000);

To handle the HTTP requests, we are using Express, a Node.js web application framework. By reading the code, you can see that it defines a route to /stocks/:symbol, so it accepts requests such as http://0.0.0.0:8000/stocks/AOUE, and respond with JSON data.

We also use the express.static module to serve the spec runner at http://0.0.0.0:8000/SpecRunner.html.

There is a requirement to circumvent the Same Origin Policy. This is a policy that dictates, for security reasons, that AJAX requests aren't allowed to be performed on domains different from the application.

This issue was first demonstrated while using HTML fixtures with the Chrome browser in Chapter 3, Testing Frontend Code, as there are some browsers with more rigid requirements than others while dealing with file:// URLs.

Using the Chrome browser inspector you can see errors in the console while opening the SpecRunner.html file with a file:// protocol (basically the way you've been doing until now):

Coding the server

Same origin policy error

By serving the runner, and all of the application and test code under the same base URL, we prevent this problem from happening, and are able to run the specs on any browser.

Running the server

To run the server, first you need to install its dependencies (Express) using Node's package manager. Inside the application root folder, run the npm command:

$ npm install express

This command will download Express and place it inside a new folder called node_modules inside the project folder.

Now you should be able to run the server, by invoking the node command:

$ node server.js

To check if it is working, hit http://0.0.0.0:8000/stocks/AOUE on your browser, and you should receive the JSON response:

{
  "sharePrice": "23.66"
}

Now that we have our server dependency working, we can get back to writing the spec.

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

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