I believe that i couldn'd configure the axios-mock-adapter. My files are:
axiosConfig.ts
const axiosInstance = axios.create({
baseURL: 'http://localhost:3000', // Localhost
headers: {
'Content-Type': 'application/json',
},
});
export default axiosInstance;
mockAxios.ts
import MockAdapter from 'axios-mock-adapter';
import axiosInstance from './axiosConfig';
const mockAxios = new MockAdapter(axiosInstance, { delayResponse: 200 });
// Mock responses
const projects = [
{ id: 1, name: 'Project 1' },
{ id: 2, name: 'Project 2' },
{ id: 3, name: 'Project 3' },
{ id: 4, name: 'Project 4' },
{ id: 5, name: 'Project 5' },
];
mockAxios.onGet('/projects/fetchAll').reply(200, { data: projects });
export default mockAxios;
projectsApi.ts
import axios from 'axios';
const fetchAllProjects = async () => {
console.log('Fetching all projects');
const res = await axios.get('/projects/fetchAll');
console.log(res);
return res;
}
export { fetchAllProjects };
I tried to call it like const response = await fetchAllProjects(); console.log(response);
but this call gets 404 error in projectsApi.ts file since it prints Fetching all projects but no res.
I don't know what else to do but I tried to use mockAxios.onAny() call. Other posts here didn't solve my issue.
You didn't use the configured axiosInstance
.
You should call the API function after mocking.
e.g.
axiosConfig.ts
:
import axios from 'axios';
const axiosInstance = axios.create({
baseURL: 'http://localhost:3000', // Localhost
headers: {
'Content-Type': 'application/json',
},
});
export default axiosInstance;
projectsApi.ts
:
import axiosInstance from './axiosConfig';
const fetchAllProjects = async () => {
console.log('Fetching all projects');
const res = await axiosInstance.get('/projects/fetchAll');
console.log(res.data);
return res;
};
export { fetchAllProjects };
main.ts
:
import './mockAxios';
import { fetchAllProjects } from './projectsApi';
function main() {
fetchAllProjects();
}
main();
Execution result:
$ npx ts-node ./main.ts
Fetching all projects
{
data: [
{ id: 1, name: 'Project 1' },
{ id: 2, name: 'Project 2' },
{ id: 3, name: 'Project 3' },
{ id: 4, name: 'Project 4' },
{ id: 5, name: 'Project 5' }
]
}