加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – AngularJS测试在promise中调用了promise

发布时间:2020-12-17 07:07:41 所属栏目:安全 来源:网络整理
导读:我在服务中有这个方法: this.getCoords = function() { var deferred = $q.defer(); geolocation.getLocation().then(function(data) { // line 29 in Karma output var coords = _.pick(data.coords,'latitude','longitude'); return deferred.resolve(coo
我在服务中有这个方法:

this.getCoords = function() {
  var deferred = $q.defer();

  geolocation.getLocation().then(function(data) { // line 29 in Karma output
    var coords = _.pick(data.coords,'latitude','longitude');
    return deferred.resolve(coords);
  },function(reason) {
    return deferred.reject(reason);
  });

  return deferred.promise;
};

由于地理定位本身就是一个模块,我只想测试geolocation.getLocation()的确已被调用.

到目前为止我做了什么:

...

 geolocationGetLocationSpy = spyOn(geolocation,'getLocation');

 ...

 describe('getCoords()',function() {

   it('should call geolocation.getLocation()',function() {
     Googlemaps.getCoords(); // line 64 in Karma output

     // promise won't get resolved until a digest
     $rootScope.$apply();

     expect(geolocationGetLocationSpy).toHaveBeenCalled();
   });

 });

但是我得到:

PhantomJS 1.9.2 (Mac OS X) Service: Googlemaps getCoords() should call geolocation.getLocation() FAILED
    TypeError: 'undefined' is not an object (evaluating 'geolocation.getLocation().then')
        at /Users/jviotti/Projects/Temporal/angular/angular-geolocation/app/scripts/services/googleMaps.js:29
        at /Users/jviotti/Projects/Temporal/angular/angular-geolocation/test/spec/services/googleMaps.js:64

我还该怎么办?

解决方法

你使用的模式似乎很好.试着这样做:

geolocationGetLocationSpy = spyOn(geolocation,'getLocation').andCallThrough();

// or the Jasmine 2.0 syntax
geolocationGetLocationSpy = spyOn(geolocation,'getLocation').and.callThrough();

当你监视一个方法时,原始方法会被一个使所有“间谍”功能都工作的方法所覆盖.那个虚假版本的getLocation()没有返回与原始方法相同的值(原始方法似乎返回一个promise).

要做到这一点,你可以添加andCallThrough(),现在假冒版本的getLocation()将调用原始方法以及执行“间谍”功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读