是否可以使用axios-mock-adapter在模拟回复中应用passThrough()? [英] Is it possible to apply passThrough() within a mock reply using axios-mock-adapter?

查看:136
本文介绍了是否可以使用axios-mock-adapter在模拟回复中应用passThrough()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:

NodeJS 8.1.2
axios 0.16.2
axios-mock-adapter 1.9.0

测试JSON-RPC端点,我是否可以执行以下操作:

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

推荐答案

您可以通过将调用传递给reply回调中的原始适配器来实现:

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

本质上是passThrough()所做的.

这篇关于是否可以使用axios-mock-adapter在模拟回复中应用passThrough()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆