Question

I want to test my google maps geocoder directive. There, I have a geocode constructor which I already stubbed:

...
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());
    }});
}

My stubbing code:

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

I want to test geocode.geocoder() if it has been called. Therefore, I think I need to tell the stub that it has this method which is normally created by the constructor google.maps.Geocoder().

Is stubbing the right way to do this anyway?

Était-ce utile?

La solution

You could have in your test:

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

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

So here you said that your new $window.google.maps.Geocoder() returns geocodeInstance which has a method geocode. Also i used sinon.spy() because you just wanted to test that it was called. It can be a stub as well.

And later on:

expect(geocodeInstance.geocode).calledOnce;

I used expect since it's the way I am used to write my tests. Also try changing in your directive and inject $window and do:

geocoder = new $window.google.maps.Geocoder();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top