Pubudu Jayasanka
Pubudu Jayasanka

Reputation: 1462

How to work with path parameters in Axios Mock adapter

I am using axios mock adapter to mock the data for my react front-end. Currently I am working with param and it was working. But i need to support it to following url

.../invoice/1

This is my code

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

Upvotes: 9

Views: 15402

Answers (3)

Ezequiel Gimenez
Ezequiel Gimenez

Reputation: 53

Following @NearHuscarl answer; and fixing

Do not access Object.prototype method hasOwnProperty from target object. eslintno-prototype-builtins

you could:

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 (Object.prototype.hasOwnProperty.call(result, key)) {
      result[key] = [result[key], val];
    } else {
      result[key] = val;
    }
  });

  return result;
}

that is, replacing result.hasOwnProperty(key) with Object.prototype.hasOwnProperty.call

Upvotes: 0

NearHuscarl
NearHuscarl

Reputation: 81565

For anyone who also wants to get the js object from dynamic query string of the url

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

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"}

Live Demo

Edit Axios Mock Dynamic Query String

Upvotes: 5

cssiamamess
cssiamamess

Reputation: 126

Since this is one of the top results when searching for "axios mock adaptor with token in path", I'll just point out that the GitHub README for axios mock adaptor has the solution. https://github.com/ctimmerm/axios-mock-adapter

You can pass a Regex to .onGet, so for your case -

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

That should pick up your calls to /invoice/${id}

Upvotes: 7

Related Questions