mardi 5 avril 2016

Unit Test to make sure a function calls through to an api and assigns the data to a variable

I am working on writing and JS unit test. This is something that I still struggle with and am learning how to do properly. I have a function that calls through to an api and then assigns the data from the promise to a variable. Below is the code:

API

this.get_history = function(item_id) {
var deferred = $q.defer();
$http.get('/api/items/' + item_id + '/bids', {
    ignoreLoadingBar: true
  })
  .success(function(data, status, headers, config) {
    deferred.resolve(data);
  })
  .error(function(data, status, headers, config) {
    deferred.reject(data);
  });
 return deferred.promise;
};

Function that calls API

item.refresh_bid_history = function() {
  var self = this;
  my_api.get_history(self.id).then(function(data){self.bid_history = data});
};

I am trying to write a test that either makes sure the api gets called, and/or that the data part actually gets assigned to the item.bid_history attribute. Below is the test that I have now.

Test

it ('refresh_bid_history calls get_item_bid_history API', inject(function () {
  var item_json = mock_item_details_json();
  var item = ItemService.get_item(fb_ref, item_json);
  item.bid_history = [];
  item.refresh_bid_history();
  expect(item.bid_history.length).toEqual(1);
  expect(item.bid_history[0].placed_at._d).toBeDefined();
}));

If you need more info I can try and provide it.

Aucun commentaire:

Enregistrer un commentaire