I'm testing geolocation using JsTestDriver, this is my code:
GeoLocationTest.prototype.testLocation = function(){
expectAsserts(1);
var coordinate = new Coordinate();
var location = coordinate.getLocation();
assertEquals("1,1",location);
};
Te test always fails because it tests immediately, before getting the geolocation coordinates. I tried using a timeout but the test also executes immediately.
setTimeout(function(){assertEquals("1,1",location);},10000);
And this is the javascript I'm trying to test
function Coordinate () {
this.latitude = 0.0;
this.longitude = 0.0;
this.date = new Date();
this.errorMsg = "";
}
Coordinate.prototype.getLocation = function(){
if (this.isBrowserSupported()){ //this test passes
navigator.geolocation.getCurrentPosition(this.setPosition,this.setError);
return "" + this.latitude + "," + this.longitude;
}
return "Browser not supported";
}
Coordinate.prototype.setPosition = function(position){
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
}
AssertError: expected "1,1" but was "0,0"
I was doing it wrong, hate JS
function Coordinate () {
latitude = 0.0;
longitude = 0.0;
date = new Date();
errorMsg = "";
}
Coordinate.prototype.getLocation = function(){
if (this.isBrowserSupported()){ //this test passes
navigator.geolocation.getCurrentPosition(this.setPosition,this.setError);
return 0;
}
return -1;
}
Coordinate.prototype.setPosition = function(position){
Coordinate.prototype.latitude = position.coords.latitude;
Coordinate.prototype.longitude = position.coords.longitude;
}
And then the test
GeoLocationTest.prototype.testLocation = function(){
var timeout = 10000;
expectAsserts(2);
var coordinate = new Coordinate();
coordinate.getLocation();
setTimeout(function(){
assertEquals(1,Coordinate.prototype.latitude);
assertEquals(1,Coordinate.prototype.longitude);
console.log("testLocation finished");
},timeout);
};
JsTestDriver will output "AssertError: Expected '2' asserts but '0' encountered."
So open the browser, open the console and wait for the test to execute. I added the last log because if the test passes nothing happens, if it fails it outputs the failure.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.