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;
};
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With