2017-04-07 54 views
0

我试图使用node-geocoder npm包来获取位置的纬度和经度的一些对象。返回JavaScript承诺拒绝履行价值

请帮我理解JavaScript的承诺。

下面是一个例子代码:

import nodeGeocoder from 'node-geocoder' 

function getLocation (str) { 
    // Selecting Google as provider 
    const geocoder = nodeGeocoder({ 
     provider: 'google', 
    }) 

    return geocoder.geocode(str) 
     .then(response => { 
      // I want to return latitude an longitude 
      return [response[0].latitude, response[0].longitude] 
     }) 
     .catch(error => { 
      console.log(`Geocoder Error: ${ error }`) 
     }) 
} 

export default getLocation 

大二这是一个测试(玩笑框架):

import getLocation from './index' 

test('Checking',() => { 
    expect(getLocation('29 champs elysée paris')).toEqual([48.8698679, 2.3072976]) 
}) 

当我试图用这个测试我只是得到承诺地位{"fulfillmentValue": undefined, "isFulfilled": false, "isRejected": false, "rejectionReason": undefined}

但我需要得到只是承诺解决的结果。我该怎么做?

我不希望编辑测试

+0

您无法返回尚未到达的结果。等待你必须履行的承诺。 – Bergi

回答

1

为了进行测试,大部分测试套件提供所有的承诺为基础的测试异步回调。我希望它(双关语意)这样的工作:

import getLocation from './index' 

test('Checking', (done) => { 
    getLocation('29 champs elysée paris').then(geoData => { 
    expect(geoData).toEqual([48.8698679, 2.3072976]); 
    done(); 
    }).catch(error => { 
    done(error) 
    }); 
}); 

根据您可能正在使用的测试框架,你可以调用解析器回调的方式(即:done())可以改变。但是,模式应该或多或少相同。

+0

但我不想更新测试。如果我在测试中更改数组中的值 - 测试也将成功通过 –

+0

您使用的测试框架是什么? – Bwaxxlo