Wednesday, June 3, 2015

Using $httpBackend to mock up E2E Web Service API

Define a module in your cross cutting common services folder to set up the mock interceptor to the backend web services. This module would be injected as a dependency in your main module, and commented out when the actual RESTful API is available. Note that Angular has ngResource that makes it easy to work with a RESTFul API.

In the mocking module, do something like this:

var orders = [
       {
           orderId : 1,
           orderDate : Date.now(),
           totalPrice: 45.89,
           category : "online"
       },
       {
           orderId : 2,
           orderDate : Date.now(),
           totalPrice: 35.55,
           category : "in-store"
       },
       //more order objects
];

var orderUrl = "/api/orders";

//get all Orders
$httpBackend.whenGET(orderUrl).respond(orders)

//get single Order - use a regex
var editingRegex = new RegExp(orderUrl + "/[0-9][0-9]*", '');

$httpBackend.whenGET(editingRegex).respond( function(method, url, data)
    var order = { orderId: 0 };
    var parameters = url.split('/');
    var length = parameters.length;
    var id = parameters[length - 1];

    if (id > 0) {
        for (var i=0;i<orders.length;i++) {
              if (orders[i].orderId === id) {
                   order = orders[i];
                   break;
       };
    }
    return [200, order, {}];
);


//Save or edit an order
$httpBackend.whenPOST(orderUrl).respond(function (method, url, data) {
      var order = angular.fromJSON(data);
       
      if (!order.orderId) { //new order
          order.orderId = orders[orders.length - 1].orderId + 1;
          orders.push(order);
      }
      else { //update order
          for (var i=0;i<orders.length;i++) {
                if (orders[i].orderId === order.orderId) {
                    orders[i] = order;
                    break;
                 }
          };
      }
      return [200, order, {}];

});

//Ignore any other assets the app needs that we should not be intercepting
$httpBackend.whenGET("/app/").passThrough();


Voila! Using this mockup, the application will add new Orders to the in-memory array of Orders without the need to touch a backend API.

For more details, read up
https://docs.angularjs.org/api/ngMockE2E/service/$httpBackend

No comments:

Post a Comment