【问题标题】:Overwrite a function of a stub覆盖存根的函数
【发布时间】:2014-02-28 13:46:19
【问题描述】:

我想测试我的谷歌地图地理编码器指令。在那里,我有一个我已经存根的地理编码构造函数:

...
link: function(scope) {
    var map,
        geocoder,
        myLatLng,
        mapOptions = {
            zoom: 1,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

    geocoder = new google.maps.Geocoder();
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    geocoder.geocode({'address': 'New York'}, function(results, status) {
        myLatLng = new google.maps.LatLng(results[0].geometry.location.lat(),
            results[0].geometry.location.lng());
    }});
}

我的存根代码:

MapsGeocoderStub = sinon.stub();
$window.google = {
    maps: {
        Geocoder: MapsGeocoderStub
    }
};

我想测试geocode.geocoder() 是否已被调用。因此,我想我需要告诉存根它有这个通常由构造函数google.maps.Geocoder()创建的方法。

不管怎样,存根是正确的方法吗?

【问题讨论】:

  • 你能在你的第一个代码块中显示更多代码吗?
  • 恐怕你的代码是不可测试的。为了测试具有依赖项的代码(在您的情况下为geocoder),必须将依赖项注入函数而不是像这样使用new
  • 为了使您的代码可测试,所有依赖项,如 geocodermap 都应该作为服务创建并注入到指令中。当您进行单元测试时,您可以轻松地模拟这些对象。

标签: javascript angularjs angularjs-directive karma-runner sinon


【解决方案1】:

你可以在你的测试中:

var geocodeInstance = {
    geocode: sinon.spy()
};

$window.google = {
    maps: {
        Geocoder: sinon.stub().returns(geocodeInstance);
    }
};

所以你在这里说你的新 $window.google.maps.Geocoder() 返回 geocodeInstance 它有一个方法 geocode。我也使用了 sinon.spy() 因为你只是想测试它是否被调用。它也可以是存根。

后来:

expect(geocodeInstance.geocode).calledOnce;

我使用了 expect,因为这是我用来编写测试的方式。 还可以尝试更改您的指令并注入 $window 并执行以下操作:

geocoder = new $window.google.maps.Geocoder();

【讨论】:

  • 我搞错了。我编辑了答案,测试通过了。
猜你喜欢
  • 2011-09-01
  • 2010-10-25
  • 2011-02-13
  • 1970-01-01
  • 2016-02-27
  • 2010-10-30
  • 2015-03-12
  • 2011-05-31
相关资源
最近更新 更多