8

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;
};
NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Pubudu Jayasanka
  • 1,294
  • 4
  • 18
  • 34

2 Answers2

6

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}

cssiamamess
  • 116
  • 1
  • 4
3

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

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
  • Great solution, but i stuck into 1 problem. `axios.get("/api/posts?page=1")` will return the `page` object, but if i try to use `axios.get("/api/posts", {params: 1})`, the `config.url` is `/api/posts` without the `page` parameter (note this only applied on mockInstance). Any solution? codesandbox: https://codesandbox.io/s/axios-mock-dynamic-query-string-forked-q9h81x – David Yappeter Jul 07 '22 at 06:29