Ho un servizio API in cui ho diversi metodi per effettuare chiamate alle API. Ho testato con successo tutte le richieste GET ma ho problemi a testare le richieste POST.
Questo è il metodo:
export default class ApiService {
static makeApiCall = <T>(
url: string,
oneCb: <T>(d: Data) => T,
secondCb: (d: T) => void,
errorCb?: (a: ErrorModel) => void,
method = 'get',
data = {},
): Promise<void> => {
const config: AxiosRequestConfig = {};
if (method === 'post') {
config.headers = header;
return ApiClient.post(url, data, config)
.then(res => callback(normalizeCallback(res.data))).catch(error => someHandler(error));
} else {
return ApiClient.get(url)
.then(res => callback(normalizeCallback(res.data))).catch(error => someHandler(error));
}
};
// ONLY ONE POST METHOD TO MAKE IT MORE CLEAR
static someArchiveMethod = (
callback: (a: SuccessModel) => void,
errorCallback: (error: ErrorModel) => void,
cardId: string
): Promise<void> => {
return ApiService.makeApiCall<SuccessfulResponse>(
'appreciationCard/archive',
Normalizer.successfulResponse,
callback,
errorCallback,
'post',
{ cardId }
);
};
// HERE BELOW THE GET METHODS
static getPeople = (cb: (a: PeopleModel[]) => void, page?: number, limit?: number): Promise<void> => {
const queryDetails = { page, limit };
return ApiService.makeApiCall<PeopleModel[]>(
`people?${toQueryString(queryDetails)}`,
Normalizer.normalizePeople,
callback
);
};
};
Ecco come sto testando tutto ciò che riguarda i GET:
describe('apiService', () => {
beforeAll(() => {
expect(ApiClient.defaults.headers.common.Authorization).toBe('Bearer test token');
// @ts-ignore
ApiClient.get.mockImplementation((url: string) => {
return Promise.resolve({ data: mockData });
});
});
it('should call api client method', () => {
ApiService.makeApiCall(
'testUrl',
data => data,
res => res,
err => err,
'get'
);
expect(ApiClient.get).toBeCalledTimes(1);
expect(ApiClient.get).toBeCalledWith('testUrl');
});
it('should call callbacks consequently', done => {
ApiService.makeApiCall('testUrl', firstCallback, secondCallback).then(() => {
expect(firstCallback).toBeCalledTimes(1);
expect(firstCallback).toBeCalledWith(mockData);
expect(secondCallback).toBeCalledTimes(1);
expect(secondCallback).toBeCalledWith(firstCallback(mockData));
done();
});
});
});
describe('api service error flow', () => {
beforeAll(() => {
// @ts-ignore
ApiClient.get.mockImplementation((url: string) => {
console.log('error result');
return Promise.reject(mockError);
});
});
it('should handle error', done => {
console.error = jest.fn();
const firstCallback = jest.fn((data: any) => data);
const secondCallback = jest.fn((data: any) => data);
ApiService.makeApiCall('testUrl', firstCallback, secondCallback).then(() => {
expect(firstCallback).toBeCalledTimes(0);
expect(secondCallback).toBeCalledTimes(0);
expect(console.error).toBeCalledTimes(1);
expect(console.error).toBeCalledWith('ApiClient testUrl', mockError);
done();
});
});
});
describe('apiService methods', () => {
beforeAll(() => {
ApiClient.get.mockImplementation((url: string) => {
expect(ApiClient.defaults.headers.common.Authorization).toBe('Bearer test token');
return Promise.resolve({ data: mockData });
});
});
it('getPeople method call with one param', () => {
ApiService.getPeople(jest.fn(), 1, 1).then(() => {
expect(ApiClient.get).toBeCalledWith('people?page=1&limit=1');
});
});
})
Ho pensato che solo cambiando tutte le istanze di ApiClient.get
per ApiClient.post
il corretto funzionamento per verificare le richieste POST. Ma quando provo a farlo, lo dice can not read mockImplementation of undefined
. Ho provato a cambiare i metodi nei test per utilizzare il post
parametro al fine di sovrascrivere il parametro method = 'get'
ma non ho successo, ottengo questo errore
TypeError: apiClient_1.default.post non è una funzione
qualche idea?
return ApiClient.post(url, data, config) .then(res => callback(normalizeCallback(res.data))).catch(error => someHandler(error));
e funziona correttamente quando provo a fare una richiesta post. Voglio dire, ho 17 richieste di post funzionanti come devono. Allora perché nei test non funzionano allora?
get
test ma ho invece cambiato tutte le istanze di get
e impostate post
.
ApiClient
non ha metodopost
.