单元测试以确保函数调用api并将数据分配给变量

时间:2016-04-05 15:20:57

标签: javascript angularjs unit-testing

我正在写作和JS单元测试。这是我仍在努力的事情,我正在学习如何正确地做。我有一个调用api的函数,然后将promise中的数据分配给变量。以下是代码:

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;
};

调用API的函数

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

我正在尝试编写一个测试,以确保调用api,和/或数据部分实际上被分配给item.bid_history属性。以下是我现在的测试。

测试

it ('refresh_bid_history calls get_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();
}));

如果您需要更多信息,我可以尝试并提供。

1 个答案:

答案 0 :(得分:2)

当您的API返回承诺时,您的expect不应该有效,因为执行expect时,您的item.bid_history不会更新。

您可以使用Mocha直接测试您的API get_history。最新版本具有测试Promise的原生支持,请参阅此文章:Mocha With Promises

或者如果你想测试你的服务,这里是我的test example todoMVC。也许你可以从中得到一些想法。

简化:

  1. 使用$httpBackend模拟后端;
  2. 运行您的服务;
  3. 验证结果。