Pub*_*nka 7 javascript testing axios axios-mock-adapter
我正在使用 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)];
});
}
Run Code Online (Sandbox Code Playgroud)
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);
}
};
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
由于这是搜索“路径中带有令牌的 axios 模拟适配器”的最佳结果之一,我将指出 axios 模拟适配器的 GitHub README 有解决方案。https://github.com/ctimmerm/axios-mock-adapter
您可以将正则表达式传递给.onGet,因此对于您的情况 -
const pathRegex = new Regexp(`${apiUrl}\/invoice\/*`);
mock
.onGet(pathRegex).reply
...etc.etc.
Run Code Online (Sandbox Code Playgroud)
那应该接听你的电话 /invoice/${id}
| 归档时间: |
|
| 查看次数: |
4406 次 |
| 最近记录: |