2

Environment:

NodeJS 8.1.2
axios 0.16.2
axios-mock-adapter 1.9.0

Testing a JSON-RPC endpoint, am I able to do something like this:

const mockHttpClient = new MockAdapter(axios, { delayResponse: 50 })

mockHttpClient.onPost().reply((config) => { // Capture all POST methods
  const dataObj = JSON.parse(config.data) // Example data: '{"jsonrpc":"2.0","method":"getProduct","params":[123],"id":0}'

  if (dataObj.method === 'getProduct') { // Recognised method, provide mock response override
    return [200, { jsonrpc: '2.0', id: 0, result: { productId: 123, productName: 'Lorem' } }]
  }

  // TODO: PassThrough for all non-recognised methods
})

mockHttpClient.onAny().passThrough() // Allow pass through on anything that's not a POST method
Trav L
  • 14,732
  • 6
  • 30
  • 39

1 Answers1

0

You can do that by passing the call to the original adapter within the reply callback :

mockHttpClient.onPost().reply((config) => { // Capture all POST methods
  const dataObj = JSON.parse(config.data) // Example data: '{"jsonrpc":"2.0","method":"getProduct","params":[123],"id":0}'

  if (dataObj.method === 'getProduct') { // Recognised method, provide mock response override
    return [200, { jsonrpc: '2.0', id: 0, result: { productId: 123, productName: 'Lorem' } }]
  }

  // PassThrough for all non-recognised methods
  return mockHttpClient.originalAdapter(config);
})

It's essentially what passThrough() does.

Mohamed Gharib
  • 2,387
  • 1
  • 15
  • 16