【问题标题】:Geolocation unit test with JsTestDriver使用 JsTestDriver 进行地理定位单元测试
【发布时间】:2013-09-15 21:21:34
【问题描述】:

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

【问题讨论】:

    标签: javascript unit-testing


    【解决方案1】:

    我做错了,讨厌 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'遇到。”

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多