test the axios.create argument

This commit is contained in:
Simone Taeggi 2022-11-18 16:04:14 +01:00
parent 3c3cab3cad
commit feab74b178
2 changed files with 43 additions and 39 deletions

View File

@ -1,7 +1,12 @@
import axios from 'axios'; import axios from 'axios';
import { auth } from '@strapi/helper-plugin'; import { auth } from '@strapi/helper-plugin';
export const instance = axios.create({ // eslint-disable-next-line import/no-mutable-exports
export let instance;
export const getFetchClient = () => {
if (!instance) {
instance = axios.create({
baseURL: process.env.STRAPI_ADMIN_BACKEND_URL, baseURL: process.env.STRAPI_ADMIN_BACKEND_URL,
}); });
@ -32,8 +37,8 @@ instance.interceptors.response.use(
throw error; throw error;
} }
); );
}
export const getFetchClient = () => {
return { return {
get: (url, config) => instance.get(url, config), get: (url, config) => instance.get(url, config),
put: (url, data, config) => instance.put(url, data, config), put: (url, data, config) => instance.put(url, data, config),

View File

@ -1,9 +1,10 @@
import { auth } from '@strapi/helper-plugin'; import { auth } from '@strapi/helper-plugin';
import { getFetchClient } from '../getFetchClient'; import { getFetchClient, instance } from '../getFetchClient';
const token = 'coolToken'; const token = 'coolToken';
auth.getToken = jest.fn().mockReturnValue(token); auth.getToken = jest.fn().mockReturnValue(token);
auth.clearAppStorage = jest.fn().mockReturnValue(token); auth.clearAppStorage = jest.fn().mockReturnValue(token);
process.env.STRAPI_ADMIN_BACKEND_URL = 'http://localhost:1337';
describe('ADMIN | utils | getFetchClient', () => { describe('ADMIN | utils | getFetchClient', () => {
it('should return the 4 HTTP methods to call GET, POST, PUT and DELETE apis', () => { it('should return the 4 HTTP methods to call GET, POST, PUT and DELETE apis', () => {
@ -32,13 +33,11 @@ describe('ADMIN | utils | getFetchClient', () => {
expect(auth.clearAppStorage).toHaveBeenCalledTimes(1); expect(auth.clearAppStorage).toHaveBeenCalledTimes(1);
} }
}); });
it('should respond with status 200 to a known API', async () => { it('should respond with status 200 to a known API and create the instance with the correct base URL', async () => {
const response = getFetchClient(); const response = getFetchClient();
try {
const getData = await response.get('/admin/project-type'); const getData = await response.get('/admin/project-type');
expect(getData.status).toBe(200); expect(getData.status).toBe(200);
} catch (err) {
console.log('err', err); expect(instance.defaults.baseURL).toBe(process.env.STRAPI_ADMIN_BACKEND_URL);
}
}); });
}); });