My implementation includes the use of axios
with a custom HttpClient
class
export default class HttpClient {
constructor(baseUrl: string) {
const axiosInstance = axios.create({
validateStatus(status: number) {
return status === 200 || status === 201;
},
});
axiosInstance.interceptors.request.use((config) => {
if (AuthUtil.getAuthHeader()) config.headers = AuthUtil.getAuthHeader();
return config;
});
return new Proxy(this, {
get(_, prop) {
return (url: string, ...args: any) => {
url = baseUrl + url;
return Reflect.get(axiosInstance, prop)(url, ...args);
};
},
});
}
get<T = any, R = AxiosResponse<T>>(_url: string, _config?: AxiosRequestConfig): Promise<R> {
return Promise.resolve(null);
}
.....
}
This snippet demonstrates how the HttpClient
class is utilized in a service:
export default class UserManagementServiceImpl implements UserManagementService {
private client = new HttpClient('/api/user');
async getUser(): Promise<User> {
const res = await this.client.get('/user');
return res.data;
}
During testing, I encountered an error that prevented the successful invocation of the service method. Here is my test scenario:
describe('User actions', () => {
test('creates GET_TERMS_SUCCESS', async () => {
jest.mock('axios', () => {
return {
create: jest.fn().mockReturnValue({
interceptors: {
request: { use: jest.fn(), eject: jest.fn() },
response: { use: jest.fn(), eject: jest.fn() },
},
get: jest.fn().mockReturnValue({ data: user }),
}),
};
});
const user = await userService.getUser();
});
});
// ERROR:
/*
Error: Error: connect ECONNREFUSED 127.0.0.1:80
*/
I have explored various solutions from community forums without success. Any guidance on resolving this issue would be greatly appreciated.