I have to test this Component but I am confused about how to test it.how to pass parameters when we create instance of it. Can I use axios-mock-adapter here?? I have used this component in my project.I am new to react testing and using axios for first time. can someone please help me???
This is my ApiClient Component:
import axios from 'axios'
class ApiClient {
constructor() {
this.axiosConfig = {
baseURL: this.getURL(),
timeout: 1000 * 120, // 120seconds/2minutes
headers: {
contentType: 'application/json',
accept: 'application/json',
Authorization: `Bearer ${this.getAccessToken()}`,
},
}
this.axiosInstance = axios.create(this.axiosConfig)
}
generateCancellationToken() {
const cancelTokenSource = axios.CancelToken.source()
const cancelToken = cancelTokenSource.token
return { cancelToken }
}
/**
*
* @returns string - The accessToken if present
*/
getAccessToken() {
return window.localStorage.getItem('otaAccessToken')
}
/**
*
* @returns string - The URL if present
*/
getURL() {
return window.localStorage.getItem('otaAPIURL')
}
//saves otaAccessToken & otaAccessToken in local
setAccessTokenAndBaseURL(baseUrl, Token) {
window.localStorage.setItem('otaAccessToken', Token)
window.localStorage.setItem('otaAPIURL', baseUrl)
this.updateAxios()
}
updateAxios() {
this.axiosConfig = {
...this.axiosConfig,
baseURL: this.getURL(),
headers: {
contentType: 'application/json',
accept: 'application/json',
Authorization: `Bearer ${this.getAccessToken()}`,
},
}
this.axiosInstance = axios.create(this.axiosConfig)
}
cancelToken = this.generateCancellationToken()
/**
* @async
* @returns {Promise<AxiosResponse>}
* @params {page, pageSize, sortField, sortOrder, searchKey}
*/
async fetchOTARequests(page, pageSize, sortField, sortOrder, searchKey) {
return await this.axiosInstance.get(
'/otaRequests',
{
params: {
page: page,
pageSize: pageSize,
sortBy: sortField,
sortOrder: sortOrder,
searchValue: searchKey,
},
},
this.cancelToken,
)
}
/**
* @async
* @returns {Promise<AxiosResponse>}
*/
async validateICCID(iccId) {
return await this.axiosInstance.get('/iccIds/' + iccId, this.cancelToken)
}
/**
* @async
* @param {payLoad}
* @returns {Promise<AxiosResponse>}
*/
async createOTARequest(payLoad) {
return await this.axiosInstance.post(
'/otaRequests',
payLoad,
this.cancelToken,
)
}
}
export default new ApiClient()