使用JsTestDriver进行地理位置单元测试

时间:2013-09-15 21:21:34

标签: javascript unit-testing

我正在使用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”

1 个答案:

答案 0 :(得分: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'断言但遇到'0'。”

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