如何在Axios Mock适配器中使用路径参数

时间:2019-03-07 08:00:03

标签: axios

我正在使用axios模拟适配器模拟我的前端反应的数据。目前,我正在使用param,并且正在运行。但是我需要支持它以跟随

... /发票/ 1

这是我的代码

let mock;
if (process.env.REACT_APP_MOCK_ENABLED === 'true') {
console.log('Simulation mode is enabled ');
mock = new MockAdapter(axios);

mock
    .onGet(apiUrl + '/invoice').reply(
    (config) => {
        return [200, getMockInvoice(config.params)];
    })
    .onGet(apiUrl + '/invoices').reply(
    (config) => {
        return [200, getMockInvoices(config.params)];
    });
    }

export const getInvoice = async (id) => {
console.log(id);
try {
    const invoiceResponse = await axios.get(apiUrl + `/invoice/${id}`);
    return invoiceResponse.data;
} catch (e) {
    console.log(e);
 }
};

export const getMockInvoice = (params) => {
let invoices = mockData.invoices;
let selectedInvoice = {} ;
for(let i in invoices){
    let invoice = invoices[i];
    if(invoice.invoiceNo === params.invoiceNo){
        selectedInvoice = invoice;
    }
}
return selectedInvoice;
};

2 个答案:

答案 0 :(得分:1)

由于这是搜索“在路径中带有令牌的axios模拟适配器”时的最佳结果之一,因此,我仅指出针对axios模拟适配器的GitHub README提供了解决方案。 https://github.com/ctimmerm/axios-mock-adapter

您可以将正则表达式传递给.onGet,因此对于您的情况-

const pathRegex = new Regexp(`${apiUrl}\/invoice\/*`);
mock
    .onGet(pathRegex).reply
...etc.etc.

那应该可以接听您对/invoice/${id}的呼叫

答案 1 :(得分:0)

对于任何还想从url的 dynamic 查询字符串中获取js对象的人

mock.onGet(/api\/test\/?.*/).reply((config) => {
  console.log(config.url, parseQueryString(config.url));
  return [202, []];
});

function parseQueryString(url: string) {
  const queryString = url.replace(/.*\?/, '');

  if (queryString === url || !queryString) {
    return null;
  }

  const urlParams = new URLSearchParams(queryString);
  const result = {};

  urlParams.forEach((val, key) => {
    if (result.hasOwnProperty(key)) {
      result[key] = [result[key], val];
    } else {
      result[key] = val;
    }
  });

  return result;
}

结果

axios.get("api/test");
// api/test
// null

axios.get("api/test?foo=1&bar=two");
// api/test?foo=1&bar=two
// {foo: "1", bar: "two"}

axios.get("api/test?foo=FOO&bar=two&baz=100");
// api/test?foo=FOO&bar=two&baz=100
// {foo: "FOO", bar: "two", baz: "100"}

axios.get("api/test?foo=FOO&bar=two&foo=loo");
// api/test?foo=FOO&bar=two&foo=loo
// {foo: ["FOO", "loo"], bar: "two"}

实时演示

Edit Axios Mock Dynamic Query String