Is it possible to apply passThrough() within a mock reply using axios-mock-adapter?

只谈情不闲聊 提交于 2019-12-13 16:56:41

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/46637254/is-it-possible-to-apply-passthrough-within-a-mock-reply-using-axios-mock-adapt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!