2

环境:

NodeJS 8.1.2
axios 0.16.2
axios-mock-adapter 1.9.0

测试 JSON-RPC 端点,我能做这样的事情:

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
4

1 回答 1

0

您可以通过在reply回调中将调用传递给原始适配器来做到这一点:

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

本质上就是passThrough()这样做的。

于 2019-08-20T19:57:09.843 回答