Hello I am a bit inexperienced in Javascript and jasmine and am attempting to write some simple tests for a javascript object.
var googleMap = {
geoCode: function(code, fn) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': code
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
fn(results[0].geometry.location);
} else {
alert("ALL IS LOST");
}
})
},
render: function(LatLng) {
var mapOptions = {
zoom: 8,
center: LatLng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: LatLng
});
}
};
-Here is my jasmine script; I am attempting to make sure that the render function is being called whenever we run the geocode function...
describe("Testing of googleMap.js", function() {
it("Test GeoCode", function() {
var input = "Columbus";
spyOn(googleMap, 'render');
googleMap.geoCode(input, googleMap.render);
expect(googleMap.render).toHaveBeenCalled();
});
});
whenever I run this my specRunner returns an error claiming the expect claimed spy render to have been called, I am a bit baffled as to why it wouldn't have been.... is this to do with how I am attempting to set up my spy, or is the javascript object I made impossible to test. I am having trouble finding similar examples to work from.
The method .geocode
of the object google.maps.Geocoder
is asynchronous.
Therefore at the time of checking if the callback function was executed, you haven't got your response back and this means your function will not be called.
If all you want is to test if the function will be called then you can do something like the following:
describe("Testing of googleMap.js", function() {
it("Test GeoCode", function(done) {
var input = "Columbus";
googleMap.geoCode(input, function() {
// here you know that your callback function was called
done();
});
});
});
Or if you want still use a mock function you can do this (with jasmine 2.0):
describe("Testing of googleMap.js", function() {
it("Test GeoCode", function(done) {
var input = "Columbus";
var callbackSpy = jasmine.createSpy("callback").and.callFake(function() {
done();
});
googleMap.geoCode(input, callbackSpy);
});
});
With the given code blocks you get an timeout error if the callback function doesn't get called:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Here is a demo (with an mocked google geocoder).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments