Skip to content

Instantly share code, notes, and snippets.

@akimabs
Created October 25, 2021 08:47
Show Gist options
  • Save akimabs/82ea9a1d8f07ceda7806dfb64a93c36d to your computer and use it in GitHub Desktop.
Save akimabs/82ea9a1d8f07ceda7806dfb64a93c36d to your computer and use it in GitHub Desktop.
test mock axios
import axios, { AxiosResponse } from 'axios';
import { BaseRequest, ResultType } from 'types';
import { BASE_URL } from 'env';
/**
* Request helper for HTTPRequest
* @param params must receive Object
* @param id must receive String or Number
* @param headers must receive Object
* @param body must receive Object
* @param method from AxiosMethod type
* @param endpoint must receive Endpoint type
* and must return
* @returns { ResultType }
*/
export const request = async ({
params,
id,
headers,
body,
endpoint,
method,
}: BaseRequest): Promise<ResultType> => {
let result: ResultType = {
status: 'loading',
status_code: 0,
data: null,
};
try {
const res: AxiosResponse = await axios({
url: `${BASE_URL}${endpoint}/` + id,
method,
data: body,
headers,
params,
});
const resultSuccess: ResultType = {
status: 'success',
status_code: res.status,
data: res.data?.data,
};
return { ...result, resultSuccess };
//End of schema success
} catch ({ response }: any) {
const resError: AxiosResponse<any> | any = response;
const resultError: ResultType = {
status: 'error',
status_code: resError?.status,
data: resError?.data?.data,
};
return { ...resError, resultError };
//End of schema error
}
};
// Ini testnya
import axios from 'axios';
import { request } from 'app/utils';
import { Endpoint } from 'types';
jest.mock('axios', () => ({
get: jest.fn(),
}));
jest.runAllTimers();
test('should fetch users', () => {
const { get }: any = axios;
const users = {
id: 1,
name: 'Leanne Graham',
username: 'Bret',
email: '[email protected]',
address: {
street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874',
geo: {
lat: '-37.3159',
lng: '81.1496',
},
},
phone: '1-770-736-8031 x56442',
website: 'hildegard.org',
company: {
name: 'Romaguera-Crona',
catchPhrase: 'Multi-layered client-server neural-net',
bs: 'harness real-time e-markets',
},
};
const resp = { status: 'error', status_code: undefined, data: users };
get?.mockResolvedValue(resp);
return request({ endpoint: Endpoint.users, method: 'GET', id: 1 }).then(data =>
// expect(data).toEqual(users),
console.log('asdas', data),
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment