【问题标题】:Nock and google maps clientNock 和谷歌地图客户端
【发布时间】:2018-06-19 19:19:05
【问题描述】:

我正在尝试测试使用@google/maps 客户端获取路线数据的服务。

这是该服务的简化版本:

'use strict'

const dotenv = require('dotenv')
const GoogleMaps = require('@google/maps')

dotenv.config()
const {GOOGLE_API_KEY: key} = process.env
const client = GoogleMaps.createClient({key, Promise})

const getData = exports.getData = async function({origin, destination}) {
  try {
    const options = {
      origin,
      destination,
      mode: 'transit',
      transit_mode: ['bus', 'rail']
    }
    const res = await client.directions(options).asPromise()
    return res
  } catch (err) {
    throw err
  }
}

这是一个展示案例的测试文件:

'use strict'

const dotenv = require('dotenv')
const nock = require('nock')

const gdService = require('./gd.service')

dotenv.config()
const {GOOGLE_API_KEY: key} = process.env
const response = {json: {name: 'custom'}}
const origin = {lat: 51.5187516, lng: -0.0836314}
const destination = {lat: 51.52018, lng: -0.0998361}
const opts = {origin, destination}

nock('https://maps.googleapis.com')
  .get('/maps/api/directions/json')
  .query({
    origin: `${origin.lat},${origin.lng}`,
    destination: `${destination.lat},${destination.lng}`,
    mode: 'transit',
    transit_mode: 'bus|rail',
    key
  })
  .reply(200, response)

gdService.getData(opts)
  .then(res => {
    console.log(res.json) // it's undefined!
  })
  .catch(err => {
    console.error(err)
  })

我期望得到定义的response 作为服务方法调用的响应。但我得到undefined。这是为什么呢?

【问题讨论】:

    标签: node.js google-maps-api-3 nock


    【解决方案1】:

    看了@google/maps客户端的源码后,我发现我必须为nock提供以下回复头:

    ...
    nock('https://maps.googleapis.com')
      .defaultReplyHeaders({
        'Content-Type': 'application/json; charset=UTF-8'
      })
      .get('/maps/api/directions/json')
      ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 2018-03-26
      • 2017-10-28
      相关资源
      最近更新 更多