Question

I'm using the google.maps library inside a Backbone model like this (coffeescript):

class Route extends Backbone.Model

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

In my tests, I whenever I try to instantiate a Route, I obviously run in to an issue. How can I stub out google in my test so that it won't cause this problem?

Was it helpful?

Solution

Don't know much about coffescript, but you can give the model constructor a second object as argument.

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

Then in the initialize function you would write:

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

Now you can stub the direction service or use another one (if there is any) for single instances.

Another way would be to replace the DirectionService directly:

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top