如何使用Sinon.JS存根google.maps库?

时间:2011-11-30 16:15:14

标签: javascript google-maps backbone.js jasmine sinon

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

class Route extends Backbone.Model

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

在我的测试中,每当我尝试实例化Route时,我显然会遇到问题。如何在测试中删除google以便它不会导致此问题?

2 个答案:

答案 0 :(得分:4)

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

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

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

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

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

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

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

答案 1 :(得分:1)

尝试编写可测试代码时的主要失败之一是在要测试的对象中创建新实例。调用Inversion of control的模式有助于编写可测试的代码。诀窍是你在类中创建的所有东西都会被注入到构造函数中。这样做,在测试中你可以注入一个简单的模拟或存根。所以ProTom的答案就是关于这种模式。

另一个解决方案: 在JavaScript中,我们可以轻松地覆盖我们自己的每个对象/函数。这意味着您可以创建自己的google.map DirectionsService。顺便说一下,测试代码而不依赖于其他库更好,所以你应该用你需要的方法创建自己的google对象。