0

我正在使用 JsTestDriver 测试地理位置,这是我的代码:

GeoLocationTest.prototype.testLocation = function(){
    expectAsserts(1);
    var coordinate = new Coordinate();
    var location = coordinate.getLocation();
    assertEquals("1,1",location);
};

测试总是失败,因为它会在获取地理位置坐标之前立即进行测试。我尝试使用超时,但测试也立即执行。

setTimeout(function(){assertEquals("1,1",location);},10000);

这是我要测试的javascript

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:预期为“1,1”但为“0,0”

4

1 回答 1

0

我做错了,讨厌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;
}

然后是测试

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 将输出“AssertError: Expected '2' asserts but '0'遇到”。

于是打开浏览器,打开控制台,等待测试执行。我添加了最后一个日志,因为如果测试通过,则没有任何反应,如果失败则输出失败。

于 2013-09-15T22:59:52.630 回答