我在这样的 Backbone 模型中使用 google.maps 库(coffeescript):
class Route extends Backbone.Model
initialize: ->
@directionsService = new google.maps.DirectionsService()
在我的测试中,每当我尝试实例化 aRoute
时,显然都会遇到问题。我怎样才能google
在我的测试中存根,这样它就不会导致这个问题?
我在这样的 Backbone 模型中使用 google.maps 库(coffeescript):
class Route extends Backbone.Model
initialize: ->
@directionsService = new google.maps.DirectionsService()
在我的测试中,每当我尝试实例化 aRoute
时,显然都会遇到问题。我怎样才能google
在我的测试中存根,这样它就不会导致这个问题?
对咖啡脚本了解不多,但您可以给模型构造函数提供第二个对象作为参数。
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;
One of the main failure when you try to write testable code is to create new instances in your object you want to test. There is a pattern calling Inversion of control that helps to write testable code. The trick is that all the stuff you would create in your class will be injected into the constructor. Doing it this way, in your test you can just inject a simple mock or stub. So the answer of ProTom is about this pattern.
Another solution: In JavaScript we can easily override every object/function by our own. Which means you can create your own google.map DirectionsService. Btw it would better to test your code without any dependencies to other libs, so you should create your own google object with the methods you need.