Search code examples
node.jsgoogle-maps-api-3nock

Nock and google maps client


I'm trying to test a service that uses the @google/maps client for getting directions data.

Here is a simplified version of the service:

'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
  }
}

And here is a test file to show the case:

'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)
  })

What I expect is to get the defined response as a response of the service method invocation. But I get undefined. Why is that?


Solution

  • After reading the source of @google/maps client, I figured out that I had to provide nock with the following reply header:

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