javascript - 如何用 Sinon.JS 去除 google.maps 库?

标签 javascript google-maps backbone.js jasmine sinon

我在像这样的 Backbone 模型中使用 google.maps 库 (coffeescript):

class Route extends Backbone.Model

  initialize: ->
    @directionsService = new google.maps.DirectionsService()

在我的测试中,每当我尝试实例化一个 Route 时,我显然会遇到一个问题。我怎样才能在我的测试中去掉 google,这样它就不会导致这个问题?

最佳答案

不太了解 coffescript,但您可以为模型构造函数提供第二个对象作为参数。

var mymodel = new Route({/*attributes*/}, {directionService: yourStub});

然后在初始化函数中你会写:

initialize: function(atts, options) {
  this.directionService = options.directionService || new google.maps.DirectionsService();
}

现在您可以对方向服务 stub 或使用另一个(如果有的话)用于单个实例。

另一种方法是直接替换 DirectionService:

var origService = google.maps.DirectionsService;
google.maps.DirectionsService = function() {/*your stub*/};
var route = new Route();
google.maps.DirectionsService = origService;

关于javascript - 如何用 Sinon.JS 去除 google.maps 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8329161/

相关文章:

javascript - 从 NodeList 获取元素的索引

javascript - 需要将 UTF-8 字符串编码规范化为组合字符

google-maps - 谷歌地图偏离中心/切断

javascript - Backbone.js:在模型中设置模型属性?

javascript - 主干模型 : empty attribute with get method but in attributes object

javascript - 什么时候使用 jQuery 动画 promise 而不是回调?

javascript - 使用 setTimeout 延迟 ng-hide 执行

javascript - 将 Google map 高程输出转换为英尺而不是米

javascript - 使用 google maps js API 时是否需要隐藏 API key ?如果是这样,如何?

javascript - Backbone JS 路由无法正常工作