Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
};
like image 920
Pubudu Jayasanka Avatar asked Mar 07 '19 08:03

Pubudu Jayasanka


1 Answers

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}

like image 168
cssiamamess Avatar answered Nov 14 '22 21:11

cssiamamess