diff --git a/common/src/main/resources/ts/model/Student.ts b/common/src/main/resources/ts/model/Student.ts index cb2ae626f..717aedab5 100644 --- a/common/src/main/resources/ts/model/Student.ts +++ b/common/src/main/resources/ts/model/Student.ts @@ -1,5 +1,5 @@ import {_, notify} from 'entcore'; -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {IStructure} from "@common/model/Viescolaire"; import {IAudience} from "@common/model/Audience"; diff --git a/common/src/main/resources/ts/services/GroupService.ts b/common/src/main/resources/ts/services/GroupService.ts index 22ac3bbe6..11442b728 100644 --- a/common/src/main/resources/ts/services/GroupService.ts +++ b/common/src/main/resources/ts/services/GroupService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {User} from '@common/model/User'; import {SearchItem} from "@common/services/SearchService"; import {StudentDivisionResponse} from "@common/model/grouping"; diff --git a/common/src/main/resources/ts/services/SearchService.ts b/common/src/main/resources/ts/services/SearchService.ts index 0cf5b425e..45a0b4841 100644 --- a/common/src/main/resources/ts/services/SearchService.ts +++ b/common/src/main/resources/ts/services/SearchService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {User} from '@common/model/User'; export interface SearchItem { diff --git a/common/src/main/resources/ts/services/TimeslotClasseService.ts b/common/src/main/resources/ts/services/TimeslotClasseService.ts index 2bbb196e7..0e887d7df 100644 --- a/common/src/main/resources/ts/services/TimeslotClasseService.ts +++ b/common/src/main/resources/ts/services/TimeslotClasseService.ts @@ -1,5 +1,5 @@ import {ng} from "entcore"; -import http, {AxiosResponse} from "axios"; +import { http, HttpResponse } from 'entcore-toolkit'; import {IStructureSlot} from "@common/model"; interface TimeslotClasseService { @@ -7,33 +7,33 @@ interface TimeslotClasseService { getAllClassFromTimeslot(timeslotId: string): Promise; - createOrUpdateClassTimeslot(timeslotId: string, classId: string): Promise; + createOrUpdateClassTimeslot(timeslotId: string, classId: string): Promise; - deleteClassTimeslot(classId: string): Promise; + deleteClassTimeslot(classId: string): Promise; - deleteAllAudienceFromTimeslot(timeslotId: string): Promise; + deleteAllAudienceFromTimeslot(timeslotId: string): Promise; } export const timeslotClasseService: TimeslotClasseService = { async getAudienceTimeslot(audienceId: string): Promise { - const {data}: AxiosResponse = await http.get(`/viescolaire/timeslot/audience/${audienceId}`); + const {data}: HttpResponse = await http.get(`/viescolaire/timeslot/audience/${audienceId}`); return data as IStructureSlot; }, async getAllClassFromTimeslot(timeslotId: string): Promise { - const {data}: AxiosResponse = await http.get(`/viescolaire/timeslot/${timeslotId}`); + const {data}: HttpResponse = await http.get(`/viescolaire/timeslot/${timeslotId}`); return data as string[]; }, - async createOrUpdateClassTimeslot(timeslotId: string, classId: string): Promise { + async createOrUpdateClassTimeslot(timeslotId: string, classId: string): Promise { return http.post(`/viescolaire/timeslot/audience`, {timeslot_id: timeslotId, class_id: classId}); }, - async deleteAllAudienceFromTimeslot(timeslotId: string): Promise { + async deleteAllAudienceFromTimeslot(timeslotId: string): Promise { return http.delete(`/viescolaire/timeslot/${timeslotId}`); }, - async deleteClassTimeslot(classId: string): Promise { + async deleteClassTimeslot(classId: string): Promise { return http.delete(`/viescolaire/timeslot/audience/${classId}`); } } diff --git a/common/src/main/resources/ts/services/UserService.ts b/common/src/main/resources/ts/services/UserService.ts index bab5b870c..ae23230db 100644 --- a/common/src/main/resources/ts/services/UserService.ts +++ b/common/src/main/resources/ts/services/UserService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {Student} from "@common/model/Student"; export interface IUserService { diff --git a/common/src/main/resources/ts/services/ViescolaireService.ts b/common/src/main/resources/ts/services/ViescolaireService.ts index 2e5c04fc9..2245d8940 100644 --- a/common/src/main/resources/ts/services/ViescolaireService.ts +++ b/common/src/main/resources/ts/services/ViescolaireService.ts @@ -1,6 +1,6 @@ import {model, ng} from 'entcore' import {ISchoolYearPeriod, IStructure, IStructureSlot} from "../model"; -import http from "axios"; +import { http } from 'entcore-toolkit'; import {Student} from "@common/model/Student"; declare let window: any; diff --git a/common/src/main/resources/ts/services/__tests__/search.service.test.ts b/common/src/main/resources/ts/services/__tests__/search.service.test.ts index 6cad45f58..8b5550faa 100644 --- a/common/src/main/resources/ts/services/__tests__/search.service.test.ts +++ b/common/src/main/resources/ts/services/__tests__/search.service.test.ts @@ -1,19 +1,23 @@ -// tricks to fake "mock" entcore ng class in order to use service -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {SearchService, searchService} from "@common/services"; describe('TimeslotClasseService', () => { it('returns data when API request is correctly called for search method', done => { - var mock = new MockAdapter(axios); const data = [{type: "USER", displayName: "displayName1", groupName: "groupName1"}, {type: "GROUP", displayName: "displayName2", groupName: "groupName2"}]; const structureId = "sturctureId"; const value = "value"; - - mock.onGet(`/presences/search?structureId=${structureId}&q=${value}`).reply(200, data); + const url = `/presences/search?structureId=${structureId}&q=${value}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); SearchService.search(structureId, value).then(res => { + expect(http.get).toHaveBeenCalledWith(url); expect(res[0].toString()).toEqual("displayName1 - groupName1"); expect(res[1].toString()).toEqual("displayName2"); done(); @@ -21,18 +25,17 @@ describe('TimeslotClasseService', () => { }); it('returns data when API request is correctly called for searchUser method', done => { - var mock = new MockAdapter(axios); const data = [{idClasse: ["3184$3EME1", "3487$3EME2"], classesNames: ["3EME2", "3EME1"], displayName: "displayName1"}, {idClasse: ["AMIENS-2588141165", "AMIENS-1689416"], classesNames: ["CP", "CM1"], displayName: "displayName2"}, {displayName: "displayName3"}]; const structureId = "sturctureId"; const value = "value"; const profile = "profile"; - - mock.onGet(`/presences/search/users?structureId=${structureId}&profile=${profile}&q=${value}&field=firstName&field=lastName`) - .reply(200, data); + const url = `/presences/search/users?structureId=${structureId}&profile=${profile}&q=${value}&field=firstName&field=lastName`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); SearchService.searchUser(structureId, value, profile).then((res: Array) => { + expect(http.get).toHaveBeenCalledWith(url); expect(res[0].toString()).toEqual("displayName1 - 3EME1,3EME2"); expect(res[1].toString()).toEqual("displayName2 - CM1,CP"); expect(res[2].toString()).toEqual("displayName3"); @@ -46,17 +49,16 @@ describe('TimeslotClasseService', () => { }); it('returns data when API request is correctly called for searchStudents method', done => { - var mock = new MockAdapter(axios); const data = [{idClasse: ["3184$3EME1", "3487$3EME2"], classesNames: ["3EME2", "3EME1"], displayName: "displayName1"}, {idClasse: ["AMIENS-2588141165", "AMIENS-1689416"], classesNames: ["CP", "CM1"], displayName: "displayName2"}, {displayName: "displayName3"}]; const structureId = "sturctureId"; const value = "value"; - - mock.onGet(`/presences/search/students?structureId=${structureId}&q=${value}&field=firstName&field=lastName`) - .reply(200, data); + const url = `/presences/search/students?structureId=${structureId}&q=${value}&field=firstName&field=lastName`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); SearchService.searchStudents(structureId, value).then((res: Array) => { + expect(http.get).toHaveBeenCalledWith(url); expect(res[0].toString()).toEqual("displayName1 - 3EME1,3EME2"); expect(res[1].toString()).toEqual("displayName2 - CM1,CP"); expect(res[2].toString()).toEqual("displayName3"); @@ -68,4 +70,4 @@ describe('TimeslotClasseService', () => { done(); }); }); -}); \ No newline at end of file +}); diff --git a/common/src/main/resources/ts/services/__tests__/timeslot-classe.service.test.ts b/common/src/main/resources/ts/services/__tests__/timeslot-classe.service.test.ts index 9c3c47c2c..3f718860f 100644 --- a/common/src/main/resources/ts/services/__tests__/timeslot-classe.service.test.ts +++ b/common/src/main/resources/ts/services/__tests__/timeslot-classe.service.test.ts @@ -1,18 +1,22 @@ -// tricks to fake "mock" entcore ng class in order to use service -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {timeslotClasseService, TimeslotClasseService} from "@common/services/TimeslotClasseService"; import {IStructureSlot} from "@common/model"; describe('TimeslotClasseService', () => { it('returns data when API request is correctly called for getAudienceTimeslot method', done => { const audienceId = "audienceId"; - var mock = new MockAdapter(axios); const data: IStructureSlot = {_id: "", name: "", slots: []}; - - mock.onGet(`/viescolaire/timeslot/audience/${audienceId}`).reply(200, data); + const url = `/viescolaire/timeslot/audience/${audienceId}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); timeslotClasseService.getAudienceTimeslot("audienceId").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); @@ -20,12 +24,12 @@ describe('TimeslotClasseService', () => { it('returns data when API request is correctly called for getAllClassFromTimeslot method', done => { const timeslotId = "timeslotId"; - var mock = new MockAdapter(axios); const data = ["ok"]; - - mock.onGet(`/viescolaire/timeslot/${timeslotId}`).reply(200, data); + const url = `/viescolaire/timeslot/${timeslotId}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); timeslotClasseService.getAllClassFromTimeslot("timeslotId").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); @@ -34,44 +38,49 @@ describe('TimeslotClasseService', () => { it('returns data when API request is correctly called for createOrUpdateClassTimeslot method', done => { const timeslotId = "timeslotId"; const classId = "classId"; - var mock = new MockAdapter(axios); const data = {response: true}; - - mock.onPost(`/viescolaire/timeslot/audience`, {timeslot_id: timeslotId, class_id: classId}).reply(200, data); + const url = `/viescolaire/timeslot/audience`; + const body = {timeslot_id: timeslotId, class_id: classId}; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, { + url, + method: 'post', + data: JSON.stringify(body) + })); timeslotClasseService.createOrUpdateClassTimeslot("timeslotId", "classId").then(response => { + expect(http.post).toHaveBeenCalledWith(url, body); expect(response.data).toEqual(data); - expect(response.config.url).toEqual(`/viescolaire/timeslot/audience`); - expect(response.config.data).toEqual(JSON.stringify({timeslot_id: timeslotId, class_id: classId})); + expect((response.config as any).url).toEqual(`/viescolaire/timeslot/audience`); + expect((response.config as any).data).toEqual(JSON.stringify({timeslot_id: timeslotId, class_id: classId})); done(); }); }); it('returns data when API request is correctly called for deleteAllAudienceFromTimeslot method', done => { const timeslotId = "timeslotId"; - var mock = new MockAdapter(axios); const data = {response: true}; - - mock.onDelete(`/viescolaire/timeslot/${timeslotId}`).reply(200, data); + const url = `/viescolaire/timeslot/${timeslotId}`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'delete'})); timeslotClasseService.deleteAllAudienceFromTimeslot("timeslotId").then(response => { + expect(http.delete).toHaveBeenCalledWith(url); expect(response.data).toEqual(data); - expect(response.config.url).toEqual(`/viescolaire/timeslot/${timeslotId}`); + expect((response.config as any).url).toEqual(`/viescolaire/timeslot/${timeslotId}`); done(); }); }); it('returns data when API request is correctly called for getAudienceTimeslot method', done => { const classId = "classId"; - var mock = new MockAdapter(axios); const data = {response: true}; - - mock.onDelete(`/viescolaire/timeslot/audience/${classId}`).reply(200, data); + const url = `/viescolaire/timeslot/audience/${classId}`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'delete'})); timeslotClasseService.deleteClassTimeslot("classId").then(response => { + expect(http.delete).toHaveBeenCalledWith(url); expect(response.data).toEqual(data); - expect(response.config.url).toEqual(`/viescolaire/timeslot/audience/${classId}`); + expect((response.config as any).url).toEqual(`/viescolaire/timeslot/audience/${classId}`); done(); }); }); -}); \ No newline at end of file +}); diff --git a/common/src/main/resources/ts/services/__tests__/viescolaire.service.test.ts b/common/src/main/resources/ts/services/__tests__/viescolaire.service.test.ts index 1c6027a00..35ca768e8 100644 --- a/common/src/main/resources/ts/services/__tests__/viescolaire.service.test.ts +++ b/common/src/main/resources/ts/services/__tests__/viescolaire.service.test.ts @@ -1,30 +1,37 @@ // tricks to fake "mock" entcore ng class in order to use service import {model, ng} from "@presences/models/__mocks__/entcore"; -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {ViescolaireService} from "../ViescolaireService"; import {IStructure} from "@common/model"; describe('ViescolaireService', () => { it('returns data when API request is correctly called for getSchoolYearDates method', done => { const structureId = "structureId"; - var mock = new MockAdapter(axios); const data = {response: true}; - mock.onGet('viescolaire/settings/periode/schoolyear?structureId='+structureId).reply(200, data); + const url = 'viescolaire/settings/periode/schoolyear?structureId=' + structureId; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); ViescolaireService.getSchoolYearDates("structureId").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('returns data when API request is correctly called for getSlotProfile method', done => { - var mock = new MockAdapter(axios); const data = {response: true}; - mock.onGet('/viescolaire/structures/structureId/time-slot').reply(200, data); + const url = '/viescolaire/structures/structureId/time-slot'; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); ViescolaireService.getSlotProfile("structureId").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); @@ -33,20 +40,18 @@ describe('ViescolaireService', () => { it('returns data when API request is correctly called for getStudent method', done => { const structureId = "structureId"; const studentId = "studentId"; - var mock = new MockAdapter(axios); const data = {response: true}; - mock.onGet(`viescolaire/eleves?idUser=${studentId}&idStructure=${structureId}`).reply(200, data); + const url = `viescolaire/eleves?idUser=${studentId}&idStructure=${structureId}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); ViescolaireService.getStudent("structureId", "studentId").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('returns data when API request is correctly called for getBuildOwnStructure method', done => { - var mock = new MockAdapter(axios); - const data = {response: true}; - const structure1: IStructure = {id: "id1", name: "name1"} const structure2: IStructure = {id: "id2", name: "name2"} const expected: Array = [structure1, structure2]; @@ -57,8 +62,7 @@ describe('ViescolaireService', () => { model.me.structureNames.push("name1"); model.me.structureNames.push("name2"); - mock.onGet('/viescolaire/structures/structureId/time-slot').reply(200, data); expect(ViescolaireService.getBuildOwnStructure()).toEqual(expected); done(); }); -}); \ No newline at end of file +}); diff --git a/common/src/main/resources/ts/services/grouping.service.ts b/common/src/main/resources/ts/services/grouping.service.ts index 9223be097..59c7eba5f 100644 --- a/common/src/main/resources/ts/services/grouping.service.ts +++ b/common/src/main/resources/ts/services/grouping.service.ts @@ -1,6 +1,6 @@ import {Grouping, GroupingResponse} from "@common/model/grouping"; import {ng} from "entcore"; -import http from "axios"; +import { http } from 'entcore-toolkit'; export interface GroupingService { search(structureId: string, value: string): Promise; diff --git a/common/src/main/resources/ts/services/screeb.service.ts b/common/src/main/resources/ts/services/screeb.service.ts index 0673a4893..7ced1f95a 100644 --- a/common/src/main/resources/ts/services/screeb.service.ts +++ b/common/src/main/resources/ts/services/screeb.service.ts @@ -1,5 +1,5 @@ import {appPrefix, model, ng, Service} from 'entcore'; -import http from 'axios'; +import { http } from 'entcore-toolkit'; import { eventTrack, identityProperties, diff --git a/incidents/src/main/resources/public/ts/directives/punishment-form/punishment-detention-form.ts b/incidents/src/main/resources/public/ts/directives/punishment-form/punishment-detention-form.ts index 068a2a9d7..885aa8b34 100644 --- a/incidents/src/main/resources/public/ts/directives/punishment-form/punishment-detention-form.ts +++ b/incidents/src/main/resources/public/ts/directives/punishment-form/punishment-detention-form.ts @@ -12,7 +12,7 @@ import {User} from "@common/model/User"; import {SearchService} from "@common/services"; import {PeriodFormUtils} from "@common/utils/periodForm"; import {ROOTS} from "@incidents/core/const/roots"; -import {AxiosError} from "axios"; +import { HttpError } from 'entcore-toolkit'; import {punishmentService} from "@incidents/services"; declare let window: any; @@ -231,7 +231,7 @@ export const PunishmentDetentionForm = ng.directive('punishmentDetentionForm', [ if (vm.editmode && detentionSlotToDelete.detentionField.id) { punishmentService.delete(detentionSlotToDelete.detentionField.id, window.structure.id) .then(() => toasts.confirm(lang.translate('incidents.punishment.delete.succeed'))) - .catch((e: AxiosError) => toasts.warning(e.response ? e.response.data : e.message)); + .catch((e: HttpError) => toasts.warning(e.response ? e.response.data : e.message)); } } diff --git a/incidents/src/main/resources/public/ts/models/incidents/Incidents.ts b/incidents/src/main/resources/public/ts/models/incidents/Incidents.ts index 7a41cfa02..30d72cac2 100644 --- a/incidents/src/main/resources/public/ts/models/incidents/Incidents.ts +++ b/incidents/src/main/resources/public/ts/models/incidents/Incidents.ts @@ -1,5 +1,4 @@ -import http from 'axios'; -import {Mix} from 'entcore-toolkit'; +import {Mix, http} from 'entcore-toolkit'; import {DateUtils} from '@common/utils' import {LoadingCollection} from '@common/model' import {IncidentType, Partner, Place, ProtagonistType, Seriousness} from "../../services"; diff --git a/incidents/src/main/resources/public/ts/services/IncidentService.ts b/incidents/src/main/resources/public/ts/services/IncidentService.ts index d81bb0acc..97bdff37a 100644 --- a/incidents/src/main/resources/public/ts/services/IncidentService.ts +++ b/incidents/src/main/resources/public/ts/services/IncidentService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {IncidentType, Partner, Place, ProtagonistType, Seriousness} from "@incidents/services"; import {IStudentEventRequest} from "@presences/models"; import {IStudentIncidentResponse} from "@incidents/models"; @@ -25,7 +25,7 @@ export interface IncidentService { export const incidentService: IncidentService = { getIncidentParameterType: async (structureId: string): Promise => { try { - const {data}: AxiosResponse = await http.get(`/incidents/incidents/parameter/types?structureId=${structureId}`); + const {data}: HttpResponse = await http.get(`/incidents/incidents/parameter/types?structureId=${structureId}`); return data; } catch (err) { throw err; diff --git a/incidents/src/main/resources/public/ts/services/IncidentTypeService.ts b/incidents/src/main/resources/public/ts/services/IncidentTypeService.ts index 20cefd02f..a23800ac0 100644 --- a/incidents/src/main/resources/public/ts/services/IncidentTypeService.ts +++ b/incidents/src/main/resources/public/ts/services/IncidentTypeService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; export interface IncidentType { id: number; @@ -19,9 +19,9 @@ export interface IncidentTypeRequest { export interface IncidentsTypeService { get(structureId: string): Promise; - create(incidentsTypeBody: IncidentTypeRequest): Promise; - update(incidentsTypeBody: IncidentTypeRequest): Promise; - delete(reasonId: number): Promise; + create(incidentsTypeBody: IncidentTypeRequest): Promise; + update(incidentsTypeBody: IncidentTypeRequest): Promise; + delete(reasonId: number): Promise; } export const incidentsTypeService : IncidentsTypeService = { @@ -34,15 +34,15 @@ export const incidentsTypeService : IncidentsTypeService = { } }, - create: async (incidentsTypeBody: IncidentTypeRequest): Promise => { + create: async (incidentsTypeBody: IncidentTypeRequest): Promise => { return await http.post(`/incidents/type`, incidentsTypeBody); }, - update: async (incidentsTypeBody: IncidentTypeRequest): Promise => { + update: async (incidentsTypeBody: IncidentTypeRequest): Promise => { return await http.put(`/incidents/type`, incidentsTypeBody); }, - delete: async (incidentsTypeId: number): Promise => { + delete: async (incidentsTypeId: number): Promise => { return await http.delete(`/incidents/type?id=${incidentsTypeId}`); }, }; diff --git a/incidents/src/main/resources/public/ts/services/PartnerService.ts b/incidents/src/main/resources/public/ts/services/PartnerService.ts index e597404ec..8d17cff95 100644 --- a/incidents/src/main/resources/public/ts/services/PartnerService.ts +++ b/incidents/src/main/resources/public/ts/services/PartnerService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; export interface Partner { id: number; @@ -19,9 +19,9 @@ export interface PartnerRequest { export interface PartnerService { get(structureId: string): Promise; - create(partnerBody: PartnerRequest): Promise; - update(partnerBody: PartnerRequest): Promise; - delete(partnerId: number): Promise; + create(partnerBody: PartnerRequest): Promise; + update(partnerBody: PartnerRequest): Promise; + delete(partnerId: number): Promise; } export const partnerService : PartnerService = { @@ -34,15 +34,15 @@ export const partnerService : PartnerService = { } }, - create: async (partnerBody: PartnerRequest): Promise => { + create: async (partnerBody: PartnerRequest): Promise => { return await http.post(`/incidents/partner`, partnerBody); }, - update: async (partnerBody: PartnerRequest): Promise => { + update: async (partnerBody: PartnerRequest): Promise => { return await http.put(`/incidents/partner`, partnerBody); }, - delete: async (partnerId: number): Promise => { + delete: async (partnerId: number): Promise => { return await http.delete(`/incidents/partner?id=${partnerId}`); }, }; diff --git a/incidents/src/main/resources/public/ts/services/PlaceService.ts b/incidents/src/main/resources/public/ts/services/PlaceService.ts index ccb9d2336..c970819fc 100644 --- a/incidents/src/main/resources/public/ts/services/PlaceService.ts +++ b/incidents/src/main/resources/public/ts/services/PlaceService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; export interface Place { id: number; @@ -19,9 +19,9 @@ export interface PlaceRequest { export interface PlaceService { get(structureId: string): Promise; - create(placeBody: PlaceRequest): Promise; - update(placeBody: PlaceRequest): Promise; - delete(placeId: number): Promise; + create(placeBody: PlaceRequest): Promise; + update(placeBody: PlaceRequest): Promise; + delete(placeId: number): Promise; } export const placeService : PlaceService = { @@ -34,15 +34,15 @@ export const placeService : PlaceService = { } }, - create: async (placeBody: PlaceRequest): Promise => { + create: async (placeBody: PlaceRequest): Promise => { return await http.post(`/incidents/place`, placeBody); }, - update: async (placeBody: PlaceRequest): Promise => { + update: async (placeBody: PlaceRequest): Promise => { return await http.put(`/incidents/place`, placeBody); }, - delete: async (placeId: number): Promise => { + delete: async (placeId: number): Promise => { return await http.delete(`/incidents/place?id=${placeId}`); }, }; diff --git a/incidents/src/main/resources/public/ts/services/PresenceService.ts b/incidents/src/main/resources/public/ts/services/PresenceService.ts index c94412603..8091bdc75 100644 --- a/incidents/src/main/resources/public/ts/services/PresenceService.ts +++ b/incidents/src/main/resources/public/ts/services/PresenceService.ts @@ -1,5 +1,5 @@ import {idiom as lang, ng} from 'entcore' -import http, {AxiosResponse, AxiosError} from 'axios'; +import { http, HttpResponse, HttpError } from 'entcore-toolkit'; import {Reason} from "@presences/models/Reason"; export interface IPresenceService { @@ -9,8 +9,8 @@ export interface IPresenceService { export const presenceService: IPresenceService = { getReasons: async (structureId: string): Promise => { return http.get(`/incidents/structures/${structureId}/reasons`) - .then((res: AxiosResponse) => res.data || []) - .catch((err: AxiosError) => Promise.reject(err)); + .then((res: HttpResponse) => res.data || []) + .catch((err: HttpError) => Promise.reject(err)); }, }; diff --git a/incidents/src/main/resources/public/ts/services/ProtagonistTypeService.ts b/incidents/src/main/resources/public/ts/services/ProtagonistTypeService.ts index 2a0929c36..026b4936a 100644 --- a/incidents/src/main/resources/public/ts/services/ProtagonistTypeService.ts +++ b/incidents/src/main/resources/public/ts/services/ProtagonistTypeService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; export interface ProtagonistType { id: number; @@ -19,9 +19,9 @@ export interface ProtagonistTypeRequest { export interface ProtagonistTypeService { get(structureId: string): Promise; - create(protagonistTypeBody: ProtagonistTypeRequest): Promise; - update(protagonistTypeBody: ProtagonistTypeRequest): Promise; - delete(protagonistTypeId: number): Promise; + create(protagonistTypeBody: ProtagonistTypeRequest): Promise; + update(protagonistTypeBody: ProtagonistTypeRequest): Promise; + delete(protagonistTypeId: number): Promise; } export const protagonistTypeService : ProtagonistTypeService = { @@ -34,15 +34,15 @@ export const protagonistTypeService : ProtagonistTypeService = { } }, - create: async (protagonistTypeBody: ProtagonistTypeRequest): Promise => { + create: async (protagonistTypeBody: ProtagonistTypeRequest): Promise => { return await http.post(`/incidents/protagonist/type`, protagonistTypeBody); }, - update: async (protagonistTypeBody: ProtagonistTypeRequest): Promise => { + update: async (protagonistTypeBody: ProtagonistTypeRequest): Promise => { return await http.put(`/incidents/protagonist/type`, protagonistTypeBody); }, - delete: async (protagonistTypeId: number): Promise => { + delete: async (protagonistTypeId: number): Promise => { return await http.delete(`/incidents/protagonist/type?id=${protagonistTypeId}`); }, }; diff --git a/incidents/src/main/resources/public/ts/services/PunishmentCategoryService.ts b/incidents/src/main/resources/public/ts/services/PunishmentCategoryService.ts index 57241fab8..308d55df5 100644 --- a/incidents/src/main/resources/public/ts/services/PunishmentCategoryService.ts +++ b/incidents/src/main/resources/public/ts/services/PunishmentCategoryService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {IPunishmentCategory} from "@incidents/models/PunishmentCategory"; export interface IPunishmentsCategoryService { diff --git a/incidents/src/main/resources/public/ts/services/PunishmentService.ts b/incidents/src/main/resources/public/ts/services/PunishmentService.ts index a863babcf..d04752958 100644 --- a/incidents/src/main/resources/public/ts/services/PunishmentService.ts +++ b/incidents/src/main/resources/public/ts/services/PunishmentService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosError, AxiosResponse} from 'axios'; +import { http, HttpError, HttpResponse } from 'entcore-toolkit'; import { IPunishment, IPunishmentAbsenceRequest, @@ -18,13 +18,13 @@ export interface IPunishmentService { getGroupedPunishmentId(groupedPunishmentId: string, structureId: string): Promise; - create(punishmentBody: IPunishmentBody): Promise; + create(punishmentBody: IPunishmentBody): Promise; - update(punishmentBody: IPunishmentBody): Promise; + update(punishmentBody: IPunishmentBody): Promise; - delete(punishmentId: string, structureId: string): Promise; + delete(punishmentId: string, structureId: string): Promise; - deleteGroupedPunishment(groupPunishmentId: string, structureId: string): Promise; + deleteGroupedPunishment(groupPunishmentId: string, structureId: string): Promise; exportCSV(punishmentRequest: IPunishmentRequest): void; @@ -77,7 +77,7 @@ export const punishmentService: IPunishmentService = { const dateUrl: string = `&start_at=${punishmentRequest.start_at}&end_at=${punishmentRequest.end_at}`; const urlParams: string = `${typeParams}${studentParams}${groupParams}${stateParams}`; const pageUrl: string = `&page=${punishmentRequest.page}`; - const {data}: AxiosResponse = await http.get(`/incidents/punishments${structureUrl}${dateUrl}${urlParams}${orderParams}${pageUrl}`); + const {data}: HttpResponse = await http.get(`/incidents/punishments${structureUrl}${dateUrl}${urlParams}${orderParams}${pageUrl}`); data.all.filter((punishment: IPunishment) => punishment.type.punishment_category_id === PunishmentCategoryType.DETENTION) .forEach((punishment: IPunishment) => { punishment.fields = [punishment.fields]; @@ -91,29 +91,29 @@ export const punishmentService: IPunishmentService = { async getFromId(punishmentId: string, structureId: string): Promise { const url: string = `/incidents/punishments?id=${punishmentId}&structure_id=${structureId}` - const {data}: AxiosResponse = await http.get(url); + const {data}: HttpResponse = await http.get(url); return data; }, async getGroupedPunishmentId(groupedPunishmentId: string, structureId: string): Promise { const url: string = `/incidents/punishments?grouped_punishment_id=${groupedPunishmentId}&structure_id=${structureId}` - const {data}: AxiosResponse = await http.get(url); + const {data}: HttpResponse = await http.get(url); return data; }, - async create(punishmentBody: IPunishmentBody): Promise { + async create(punishmentBody: IPunishmentBody): Promise { return http.post(`/incidents/punishments`, punishmentBody); }, - async update(punishmentBody: IPunishmentBody): Promise { + async update(punishmentBody: IPunishmentBody): Promise { return http.put(`/incidents/punishments`, punishmentBody); }, - async delete(punishmentId: string, structureId: string): Promise { + async delete(punishmentId: string, structureId: string): Promise { return http.delete(`/incidents/punishments?id=${punishmentId}&structureId=${structureId}`); }, - async deleteGroupedPunishment(groupedPunishmentId: string, structureId: string): Promise { + async deleteGroupedPunishment(groupedPunishmentId: string, structureId: string): Promise { return http.delete(`/incidents/punishments?grouped_punishment_id=${groupedPunishmentId}&structureId=${structureId}`); }, @@ -162,8 +162,8 @@ export const punishmentService: IPunishmentService = { startAt: startAt, endAt: endAt } as IPunishmentAbsenceRequest) - .then((res: AxiosResponse) => res.data.all || []) - .catch((err: AxiosError) => Promise.reject(err)) + .then((res: HttpResponse) => res.data.all || []) + .catch((err: HttpError) => Promise.reject(err)) } }; diff --git a/incidents/src/main/resources/public/ts/services/PunishmentTypeService.ts b/incidents/src/main/resources/public/ts/services/PunishmentTypeService.ts index 49146787c..8e89d4128 100644 --- a/incidents/src/main/resources/public/ts/services/PunishmentTypeService.ts +++ b/incidents/src/main/resources/public/ts/services/PunishmentTypeService.ts @@ -1,16 +1,16 @@ import {model, ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {IPunishmentType, IPunishmentTypeBody} from "@incidents/models/PunishmentType"; import rights from "@incidents/rights"; export interface IPunishmentsTypeService { get(structure_id: string): Promise; - create(punishmentsTypeBody: IPunishmentTypeBody): Promise; + create(punishmentsTypeBody: IPunishmentTypeBody): Promise; - update(punishmentsTypeBody: IPunishmentTypeBody): Promise; + update(punishmentsTypeBody: IPunishmentTypeBody): Promise; - delete(id_deleted: number): Promise; + delete(id_deleted: number): Promise; } export const punishmentsTypeService: IPunishmentsTypeService = { @@ -24,15 +24,15 @@ export const punishmentsTypeService: IPunishmentsTypeService = { } }, - create: async (punishmentsTypeBody: IPunishmentTypeBody): Promise => { + create: async (punishmentsTypeBody: IPunishmentTypeBody): Promise => { return http.post(`/incidents/punishments/type`, punishmentsTypeBody); }, - update: async (punishmentsTypeBody: IPunishmentTypeBody): Promise => { + update: async (punishmentsTypeBody: IPunishmentTypeBody): Promise => { return http.put(`/incidents/punishments/type`, punishmentsTypeBody); }, - delete: async (id_deleted: number): Promise => { + delete: async (id_deleted: number): Promise => { return http.delete(`/incidents/punishments/type?id=${id_deleted}`); }, }; diff --git a/incidents/src/main/resources/public/ts/services/SeriousnessService.ts b/incidents/src/main/resources/public/ts/services/SeriousnessService.ts index 070e8ef93..6c7c79d8b 100644 --- a/incidents/src/main/resources/public/ts/services/SeriousnessService.ts +++ b/incidents/src/main/resources/public/ts/services/SeriousnessService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; export interface Seriousness { id: number; @@ -22,9 +22,9 @@ export interface SeriousnessRequest { export interface SeriousnessService { get(structureId: string): Promise; - create(seriousnessBody: SeriousnessRequest): Promise; - update(seriousnessBody: SeriousnessRequest): Promise; - delete(seriousnessId: number): Promise; + create(seriousnessBody: SeriousnessRequest): Promise; + update(seriousnessBody: SeriousnessRequest): Promise; + delete(seriousnessId: number): Promise; } export const seriousnessService : SeriousnessService = { @@ -37,15 +37,15 @@ export const seriousnessService : SeriousnessService = { } }, - create: async (seriousnessBody: SeriousnessRequest): Promise => { + create: async (seriousnessBody: SeriousnessRequest): Promise => { return await http.post(`/incidents/seriousness`, seriousnessBody); }, - update: async (seriousnessBody: SeriousnessRequest): Promise => { + update: async (seriousnessBody: SeriousnessRequest): Promise => { return await http.put(`/incidents/seriousness`, seriousnessBody); }, - delete: async (seriousnessId: number): Promise => { + delete: async (seriousnessId: number): Promise => { return await http.delete(`/incidents/seriousness?id=${seriousnessId}`); }, }; diff --git a/incidents/src/main/resources/public/ts/services/__tests__/punishment.service.test.ts b/incidents/src/main/resources/public/ts/services/__tests__/punishment.service.test.ts index 4a9bb7e9d..6fcd023d3 100644 --- a/incidents/src/main/resources/public/ts/services/__tests__/punishment.service.test.ts +++ b/incidents/src/main/resources/public/ts/services/__tests__/punishment.service.test.ts @@ -1,5 +1,10 @@ -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {punishmentService} from '@incidents/services'; import {IPunishmentAbsenceRequest, IPunishmentBody, IPunishmentRequest} from "@incidents/models"; import {User} from "@common/model/User"; @@ -8,8 +13,6 @@ let windowSpy; describe('PunishmentService', () => { it('checks if the answers of the get with several types are correct', done => { - const mock = new MockAdapter(axios); - const punishmentRequest: IPunishmentRequest = { end_at: "end_at", groups_ids: [], @@ -29,19 +32,18 @@ describe('PunishmentService', () => { const dateUrl: string = `&start_at=start_at&end_at=end_at`; const urlParams: string = `&type_id=1&type_id=2`; const pageUrl: string = `&page=0`; - mock.onGet(`/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`) - .reply(200, dataGraph); + const url = `/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url})); punishmentService.get(punishmentRequest) .then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(dataGraph); done(); }); }); it('checks if the answers of the get with several students are correct', done => { - const mock = new MockAdapter(axios); - const punishmentRequest: IPunishmentRequest = { end_at: "end_at", groups_ids: [], @@ -61,19 +63,18 @@ describe('PunishmentService', () => { const dateUrl: string = `&start_at=start_at&end_at=end_at`; const urlParams: string = `&student_id=students_id_1&student_id=students_id_2`; const pageUrl: string = `&page=0`; - mock.onGet(`/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`) - .reply(200, dataGraph); + const url = `/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url})); punishmentService.get(punishmentRequest) .then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(dataGraph); done(); }); }); it('checks if the answers of the get with several groups are correct', done => { - const mock = new MockAdapter(axios); - const punishmentRequest: IPunishmentRequest = { end_at: "end_at", groups_ids: ["groups_id_1", "groups_id_2"], @@ -93,19 +94,18 @@ describe('PunishmentService', () => { const dateUrl: string = `&start_at=start_at&end_at=end_at`; const urlParams: string = `&group_id=groups_id_1&group_id=groups_id_2`; const pageUrl: string = `&page=0`; - mock.onGet(`/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`) - .reply(200, dataGraph); + const url = `/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url})); punishmentService.get(punishmentRequest) .then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(dataGraph); done(); }); }); it('checks if the answers of the get with several process are correct', done => { - const mock = new MockAdapter(axios); - const punishmentRequest: IPunishmentRequest = { end_at: "end_at", groups_ids: [], @@ -128,19 +128,18 @@ describe('PunishmentService', () => { const dateUrl: string = `&start_at=start_at&end_at=end_at`; const urlParams: string = `&process=value1&process=value3`; const pageUrl: string = `&page=0`; - mock.onGet(`/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`) - .reply(200, dataGraph); + const url = `/incidents/punishments${structureUrl}${dateUrl}${urlParams}${pageUrl}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url})); punishmentService.get(punishmentRequest) .then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(dataGraph); done(); }); }); it('checks if the answers of the get with several option are correct', done => { - const mock = new MockAdapter(axios); - const punishmentRequest: IPunishmentRequest = { end_at: "end_at", groups_ids: ["groups_id_1", "groups_id_2"], @@ -167,19 +166,18 @@ describe('PunishmentService', () => { const urlParams: string = `&type_id=1&type_id=2&student_id=students_id_1&student_id=students_id_2&group_id=groups_id_1&group_id=groups_id_2&process=value1&process=value3`; const orderParams: string = `&order=date&reverse=true`; const pageUrl: string = `&page=0`; - mock.onGet(`/incidents/punishments${structureUrl}${dateUrl}${urlParams}${orderParams}${pageUrl}`) - .reply(200, dataGraph); + const url = `/incidents/punishments${structureUrl}${dateUrl}${urlParams}${orderParams}${pageUrl}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url})); punishmentService.get(punishmentRequest) .then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(dataGraph); done(); }); }); it('check create response is correct', done => { - const mock = new MockAdapter(axios); - const punishmentBody: IPunishmentBody = { student_ids: [] } @@ -189,23 +187,26 @@ describe('PunishmentService', () => { dataExample: "Example" } }; - mock.onPost(`/incidents/punishments`, punishmentBody) - .reply(200, dataGraph); + const url = `/incidents/punishments`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, { + url, + method: 'post', + data: JSON.stringify(punishmentBody) + })); punishmentService.create(punishmentBody) .then(response => { - expect(response.config.data).toEqual(JSON.stringify(punishmentBody)); + expect(http.post).toHaveBeenCalledWith(url, punishmentBody); + expect((response.config as any).data).toEqual(JSON.stringify(punishmentBody)); expect(response.data).toEqual(dataGraph); expect(response.status).toEqual(200); - expect(response.config.url).toEqual(`/incidents/punishments`); - expect(response.config.method).toEqual(`post`); + expect((response.config as any).url).toEqual(`/incidents/punishments`); + expect((response.config as any).method).toEqual(`post`); done(); }); }); it('check update response is correct', done => { - const mock = new MockAdapter(axios); - const punishmentBody: IPunishmentBody = { student_ids: [] } @@ -215,64 +216,67 @@ describe('PunishmentService', () => { dataExample: "Example" } }; - mock.onPut(`/incidents/punishments`, punishmentBody) - .reply(200, dataGraph); + const url = `/incidents/punishments`; + (http.put as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, { + url, + method: 'put', + data: JSON.stringify(punishmentBody) + })); punishmentService.update(punishmentBody) .then(response => { - expect(response.config.data).toEqual(JSON.stringify(punishmentBody)); + expect(http.put).toHaveBeenCalledWith(url, punishmentBody); + expect((response.config as any).data).toEqual(JSON.stringify(punishmentBody)); expect(response.data).toEqual(dataGraph); expect(response.status).toEqual(200); - expect(response.config.url).toEqual(`/incidents/punishments`); - expect(response.config.method).toEqual(`put`); + expect((response.config as any).url).toEqual(`/incidents/punishments`); + expect((response.config as any).method).toEqual(`put`); done(); }); }); it('check delete response is correct', done => { - const mock = new MockAdapter(axios); const punishmentId: string = 'punishmentId'; const structureId: string = 'structureId'; - let dataGraph = { dataGraph: { dataExample: "Example" } }; - mock.onDelete(`/incidents/punishments?id=${punishmentId}&structureId=${structureId}`) - .reply(200, dataGraph); + const url = `/incidents/punishments?id=${punishmentId}&structureId=${structureId}`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url, method: 'delete'})); punishmentService.delete(punishmentId, structureId) .then(response => { + expect(http.delete).toHaveBeenCalledWith(url); expect(response.status).toEqual(200); expect(response.data).toEqual(dataGraph); - expect(response.config.url).toEqual(`/incidents/punishments?id=${punishmentId}&structureId=${structureId}`); - expect(response.config.method).toEqual(`delete`); + expect((response.config as any).url).toEqual(`/incidents/punishments?id=${punishmentId}&structureId=${structureId}`); + expect((response.config as any).method).toEqual(`delete`); done(); }); }); it('check deleteGroupedPunishment response is correct', done => { - const mock = new MockAdapter(axios); const groupPunishmentId: string = 'groupPunishmentId'; const structureId: string = 'structureId'; - let dataGraph = { dataGraph: { dataExample: "Example" } }; - mock.onDelete(`/incidents/punishments?grouped_punishment_id=${groupPunishmentId}&structureId=${structureId}`) - .reply(200, dataGraph); + const url = `/incidents/punishments?grouped_punishment_id=${groupPunishmentId}&structureId=${structureId}`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url, method: 'delete'})); punishmentService.deleteGroupedPunishment(groupPunishmentId, structureId) .then(response => { + expect(http.delete).toHaveBeenCalledWith(url); expect(response.status).toEqual(200); expect(response.data).toEqual(dataGraph); - expect(response.config.url).toEqual(`/incidents/punishments?grouped_punishment_id=${groupPunishmentId}&structureId=${structureId}`); - expect(response.config.method).toEqual(`delete`); + expect((response.config as any).url).toEqual(`/incidents/punishments?grouped_punishment_id=${groupPunishmentId}&structureId=${structureId}`); + expect((response.config as any).method).toEqual(`delete`); done(); }); }); @@ -311,7 +315,6 @@ describe('PunishmentService', () => { }); it('check getStudentsAbsences response is correct', done => { - const mock = new MockAdapter(axios); const start_at = "start_at"; const end_at = "end_at"; const student_ids: Array = [{id: "id_1"}, {id: "id_2"}, {id: "id_3"}]; @@ -325,11 +328,12 @@ describe('PunishmentService', () => { const data = { all: ["id_1", "id_2"] }; - mock.onPost(`/incidents/punishments/students/absences`, punishment) - .reply(200, data); + const url = `/incidents/punishments/students/absences`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'post'})); punishmentService.getStudentsAbsences(student_ids, start_at, end_at) .then(response => { + expect(http.post).toHaveBeenCalledWith(url, punishment); expect(response).toEqual(data.all); done(); }); diff --git a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsManageLightbox.ts b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsManageLightbox.ts index e208b43b1..e20237a0e 100644 --- a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsManageLightbox.ts +++ b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsManageLightbox.ts @@ -19,7 +19,7 @@ import { INCIDENTS_SERIOUSNESS_EVENT, INCIDENTS_TYPE_EVENT } from "@common/core/enum/incidents-event"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {IPunishmentTypeBody} from "../../models/PunishmentType"; import {IPunishmentCategory} from "@incidents/models/PunishmentCategory"; import {IAngularEvent} from "angular"; @@ -45,7 +45,7 @@ interface ViewModel { updateIncidentsManageLightbox(): Promise; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; chooseLevel(level: number): void; } @@ -157,7 +157,7 @@ const vm: ViewModel = { } }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { switch (vm.event.name) { case INCIDENTS_PUNISHMENT_TYPE_EVENT.TRANSMIT: { diff --git a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPartnersManage.ts b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPartnersManage.ts index c5e3b4d3b..643e0b0f6 100644 --- a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPartnersManage.ts +++ b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPartnersManage.ts @@ -1,5 +1,5 @@ import {Partner, PartnerRequest, partnerService} from "@incidents/services"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {INCIDENTS_PARTNER_EVENT} from "@common/core/enum/incidents-event"; declare let window: any; @@ -12,7 +12,7 @@ interface ViewModel { hasPartners(): boolean; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; get(): Promise; @@ -73,7 +73,7 @@ const vm: ViewModel = { await partnerService.update(form); }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.get(); } diff --git a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPlaceManage.ts b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPlaceManage.ts index 28ffb4d9c..dfce26f4c 100644 --- a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPlaceManage.ts +++ b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsPlaceManage.ts @@ -1,6 +1,6 @@ import {INCIDENTS_PLACE_EVENT} from "@common/core/enum/incidents-event"; import {Place, PlaceRequest, placeService} from "@incidents/services"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; declare let window: any; @@ -12,7 +12,7 @@ interface ViewModel { hasPlaces(): boolean; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; get(): Promise; @@ -74,7 +74,7 @@ const vm: ViewModel = { await placeService.update(form); }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.get(); } diff --git a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsProtagonistsManage.ts b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsProtagonistsManage.ts index f6be7fe92..637fc3baa 100644 --- a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsProtagonistsManage.ts +++ b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsProtagonistsManage.ts @@ -1,6 +1,6 @@ import {INCIDENTS_PROTAGONIST_TYPE_EVENT} from "@common/core/enum/incidents-event"; import {ProtagonistType, ProtagonistTypeRequest, protagonistTypeService} from "@incidents/services"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; declare let window: any; @@ -12,7 +12,7 @@ interface ViewModel { hasProtagonistTypes(): boolean; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; get(): Promise; @@ -73,7 +73,7 @@ const vm: ViewModel = { await protagonistTypeService.update(form); }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.get(); } diff --git a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsSeriousnessManage.ts b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsSeriousnessManage.ts index 238c038e7..7135f948d 100644 --- a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsSeriousnessManage.ts +++ b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsSeriousnessManage.ts @@ -1,6 +1,6 @@ import {INCIDENTS_SERIOUSNESS_EVENT} from "@common/core/enum/incidents-event"; import {Seriousness, SeriousnessRequest, seriousnessService} from "@incidents/services"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {idiom as lang} from "entcore"; import {safeApply} from "@common/utils"; @@ -15,7 +15,7 @@ interface ViewModel { hasSeriousnesses(): boolean; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; get(): Promise; @@ -84,7 +84,7 @@ export class IncidentsSeriousnessManage implements ViewModel { await seriousnessService.update(form); } - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { this.get(); } diff --git a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsTypeManage.ts b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsTypeManage.ts index 5fb281d40..4ef24db47 100644 --- a/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsTypeManage.ts +++ b/incidents/src/main/resources/public/ts/sniplets/incidents-manage/incidentsTypeManage.ts @@ -1,5 +1,5 @@ import {incidentsTypeService, IncidentType, IncidentTypeRequest} from "@incidents/services"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {INCIDENTS_TYPE_EVENT} from "@common/core/enum/incidents-event"; declare let window: any; @@ -14,7 +14,7 @@ interface ViewModel { hasIncidentsType(): boolean; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; getIncidentsType(): Promise; @@ -80,7 +80,7 @@ const vm: ViewModel = { await incidentsTypeService.update(form); }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.getIncidentsType(); } diff --git a/incidents/src/main/resources/public/ts/sniplets/punishment-form.ts b/incidents/src/main/resources/public/ts/sniplets/punishment-form.ts index ddc8ef47e..cefd5aa69 100644 --- a/incidents/src/main/resources/public/ts/sniplets/punishment-form.ts +++ b/incidents/src/main/resources/public/ts/sniplets/punishment-form.ts @@ -9,7 +9,7 @@ import {PunishmentCategoryType} from "@incidents/models/PunishmentCategory"; import {IPunishmentType} from "@incidents/models/PunishmentType"; import {User} from "@common/model/User"; import {PunishmentsUtils} from "@incidents/utilities/punishments"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; declare let window: any; @@ -57,7 +57,7 @@ interface ViewModel { deleteAll(): Promise; - validDeleteResponse(response: AxiosResponse): void + validDeleteResponse(response: HttpResponse): void getStudentsFromView(): void; @@ -218,17 +218,17 @@ const vm: ViewModel = { async delete(): Promise { vm.preparePunishmentForm(); - let response: AxiosResponse = await punishmentService.delete(vm.form.id, window.structure.id); + let response: HttpResponse = await punishmentService.delete(vm.form.id, window.structure.id); vm.validDeleteResponse(response); }, async deleteAll(): Promise { vm.preparePunishmentForm(); - let response: AxiosResponse = await punishmentService.deleteGroupedPunishment(vm.form.grouped_punishment_id, window.structure.id); + let response: HttpResponse = await punishmentService.deleteGroupedPunishment(vm.form.grouped_punishment_id, window.structure.id); vm.validDeleteResponse(response); }, - validDeleteResponse(response: AxiosResponse) { + validDeleteResponse(response: HttpResponse) { if (response.status == 200 || response.status == 201) { vm.closePunishmentLightbox(); toasts.confirm(lang.translate('incidents.punishment.delete.succeed')); diff --git a/incidents/src/main/resources/public/ts/sniplets/punishments-manage/punishmentsTypeManage.ts b/incidents/src/main/resources/public/ts/sniplets/punishments-manage/punishmentsTypeManage.ts index 00c2883a8..7d3678cdc 100644 --- a/incidents/src/main/resources/public/ts/sniplets/punishments-manage/punishmentsTypeManage.ts +++ b/incidents/src/main/resources/public/ts/sniplets/punishments-manage/punishmentsTypeManage.ts @@ -2,7 +2,7 @@ import {punishmentsTypeService} from "@incidents/services/PunishmentTypeService" import {IPunishmentType, IPunishmentTypeBody} from "@incidents/models/PunishmentType"; import {IPunishmentCategory} from "@incidents/models/PunishmentCategory"; import {punishmentsCategoryService} from "@incidents/services/PunishmentCategoryService"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {toasts} from "entcore"; import {INCIDENTS_PUNISHMENT_TYPE_EVENT} from "@common/core/enum/incidents-event"; import {PunishmentsUtils} from "@incidents/utilities/punishments"; @@ -32,7 +32,7 @@ interface ViewModel { deletePunishmentType(punishmentType: IPunishmentTypeBody): Promise; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; switchCategory(): Promise; @@ -116,7 +116,7 @@ const vm: ViewModel = { } }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.getPunishmentsType(); } diff --git a/jest.config.js b/jest.config.js index 60f22c253..57be1b717 100644 --- a/jest.config.js +++ b/jest.config.js @@ -29,6 +29,6 @@ module.exports = { "^@presences(.*)$": "/presences/src/main/resources/public/ts$1", "^@massmailing(.*)$": "/massmailing/src/main/resources/public/ts$1", "^@statistics(.*)$": "/statistics-presences/src/main/resources/public/ts$1", - '^axios$': require.resolve('axios') + "^@test-utils(.*)$": "/test-utils$1" } }; diff --git a/massmailing/src/main/resources/public/ts/controllers/home.ts b/massmailing/src/main/resources/public/ts/controllers/home.ts index ad6271476..631c206e5 100644 --- a/massmailing/src/main/resources/public/ts/controllers/home.ts +++ b/massmailing/src/main/resources/public/ts/controllers/home.ts @@ -20,7 +20,7 @@ import {MailTemplateCategory} from "@common/core/enum/mail-template-category"; import {REASON_TYPE_ID} from "@common/core/enum/reason-type-id"; import {Student} from "@common/model/Student"; import {Grouping} from "@common/model/grouping"; -import {AxiosError} from "axios"; +import { HttpError } from 'entcore-toolkit'; import incidentsRights from "@incidents/rights"; interface Filter { @@ -263,10 +263,10 @@ export const homeController = ng.controller('HomeController', ['$scope', 'route' $scope.redirectTo(`/history`); } await loadFormFilter(); - await getPunishmentTypes().catch((error: AxiosError) => { + await getPunishmentTypes().catch((error: HttpError) => { console.error(error) }); - await getReasons().catch((error: AxiosError) => console.error(error)); + await getReasons().catch((error: HttpError) => console.error(error)); vm.fetchData(); $scope.$apply(); }; @@ -301,7 +301,7 @@ export const homeController = ng.controller('HomeController', ['$scope', 'route' $scope.$apply(); resolve(undefined); }) - .catch((error: AxiosError) => { + .catch((error: HttpError) => { vm.punishmentsTypes = []; reject(error); }); diff --git a/massmailing/src/main/resources/public/ts/model/Massmailing.ts b/massmailing/src/main/resources/public/ts/model/Massmailing.ts index c2d27a266..fdf654266 100644 --- a/massmailing/src/main/resources/public/ts/model/Massmailing.ts +++ b/massmailing/src/main/resources/public/ts/model/Massmailing.ts @@ -1,5 +1,5 @@ import {Template} from '@massmailing/services'; -import http, {AxiosRequestConfig, AxiosResponse} from 'axios'; +import { http, HttpRequestConfig, HttpResponse } from 'entcore-toolkit'; import {DateUtils} from '@common/utils'; import {MailingType} from '../model/Mailing'; import {BlobUtil} from '@common/utils/blob'; @@ -204,7 +204,7 @@ export class Massmailing { async process(): Promise { if (this.type === MailingType[MailingType.PDF]) { - const config: AxiosRequestConfig = { + const config: HttpRequestConfig = { responseType: 'arraybuffer', headers: { 'Content-Type': 'application/json', @@ -212,7 +212,7 @@ export class Massmailing { } }; http.post(`/massmailing/massmailings/${this.type}`, this.toJson(), config) - .then((resp: AxiosResponse) => new BlobUtil( + .then((resp: HttpResponse) => new BlobUtil( BlobUtil.getFileNameByContentDisposition(resp.headers['content-disposition']), [resp.data], {type: 'application/pdf'}) diff --git a/massmailing/src/main/resources/public/ts/services/MailingService.ts b/massmailing/src/main/resources/public/ts/services/MailingService.ts index 4e082b842..8323459d4 100644 --- a/massmailing/src/main/resources/public/ts/services/MailingService.ts +++ b/massmailing/src/main/resources/public/ts/services/MailingService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {Mailing, MailingRequest, MailingResponse} from "../model"; export interface MailingService { diff --git a/massmailing/src/main/resources/public/ts/services/MassmailingService.ts b/massmailing/src/main/resources/public/ts/services/MassmailingService.ts index c996b33bb..eee4b6d1e 100644 --- a/massmailing/src/main/resources/public/ts/services/MassmailingService.ts +++ b/massmailing/src/main/resources/public/ts/services/MassmailingService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {Massmailing, MassmailingAnomaliesResponse, MassmailingStatusResponse} from '../model'; import {DateUtils} from '@common/utils'; diff --git a/massmailing/src/main/resources/public/ts/services/SettingsService.ts b/massmailing/src/main/resources/public/ts/services/SettingsService.ts index a60049701..34e10ff81 100644 --- a/massmailing/src/main/resources/public/ts/services/SettingsService.ts +++ b/massmailing/src/main/resources/public/ts/services/SettingsService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {MailTemplateCategory} from "@common/core/enum/mail-template-category"; export interface Template { diff --git a/massmailing/src/main/resources/public/ts/services/__tests__/massmailing.services.test.ts b/massmailing/src/main/resources/public/ts/services/__tests__/massmailing.services.test.ts index 1345817f1..d5d1a2fe7 100644 --- a/massmailing/src/main/resources/public/ts/services/__tests__/massmailing.services.test.ts +++ b/massmailing/src/main/resources/public/ts/services/__tests__/massmailing.services.test.ts @@ -1,11 +1,15 @@ -import MockAdapter from "axios-mock-adapter"; -import axios from "axios"; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {massmailingService} from "@massmailing/services"; import {MassmailingStudent} from "@massmailing/model"; describe('SettingsService', () => { it('test getStatus method', done => { - const mock = new MockAdapter(axios); const data = {response: true}; const structure: string = "structureId"; const massmailed: boolean = false; @@ -21,7 +25,7 @@ describe('SettingsService', () => { const noReasons: boolean = false; const noLatenessReasons: boolean = true; - mock.onGet('/massmailing/massmailings/status?structure=structureId' + + const url = '/massmailing/massmailings/status?structure=structureId' + '&start_at=7' + '&start_date=2022-04-12' + '&end_date=2022-04-13' + @@ -39,18 +43,18 @@ describe('SettingsService', () => { '&student=student2' + '&type=type1' + '&type=type2' + - '&massmailed=false') - .reply(200, data); + '&massmailed=false'; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); massmailingService.getStatus(structure, massmailed, reasons, punishmentTypes, sanctionsTypes, start_at, start_date, end_date, groups, students, types, noReasons, noLatenessReasons).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }) }); it('test getAnomalies method', done => { - const mock = new MockAdapter(axios); const data = {response: true}; const structure: string = "structureId"; const massmailed: boolean = false; @@ -66,7 +70,7 @@ describe('SettingsService', () => { const noReasons: boolean = false; const noLatenessReasons: boolean = true; - mock.onGet('/massmailing/massmailings/anomalies?structure=structureId' + + const url = '/massmailing/massmailings/anomalies?structure=structureId' + '&start_at=7' + '&start_date=2022-04-12' + '&end_date=2022-04-13' + @@ -84,18 +88,18 @@ describe('SettingsService', () => { '&student=student2' + '&type=type1' + '&type=type2' + - '&massmailed=false') - .reply(200, data); + '&massmailed=false'; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); massmailingService.getAnomalies(structure, massmailed, reasons, punishmentTypes, sanctionsTypes, start_at, start_date, end_date, groups, students, types, noReasons, noLatenessReasons).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }) }); it('test prefetch method', done => { - const mock = new MockAdapter(axios); const student1: MassmailingStudent = { className: "", displayName: "", @@ -121,7 +125,7 @@ describe('SettingsService', () => { const noReasons: boolean = false; const noLatenessReasons: boolean = true; - mock.onGet('/massmailing/massmailings/prefetch/mailType?structure=structureId' + + const url = '/massmailing/massmailings/prefetch/mailType?structure=structureId' + '&start_at=7' + '&start_date=2022-04-12' + '&end_date=2022-04-13' + @@ -139,13 +143,14 @@ describe('SettingsService', () => { '&student=student2' + '&type=type1' + '&type=type2' + - '&massmailed=false') - .reply(200, data); + '&massmailed=false'; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); massmailingService.prefetch(mailType, structure, massmailed, reasons, punishmentTypes, sanctionsTypes, start_at, start_date, end_date, groups, students, types, noReasons, noLatenessReasons).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }) }); -}); \ No newline at end of file +}); diff --git a/massmailing/src/main/resources/public/ts/services/__tests__/settings.services.test.ts b/massmailing/src/main/resources/public/ts/services/__tests__/settings.services.test.ts index 7c360e3d8..5d03be1bf 100644 --- a/massmailing/src/main/resources/public/ts/services/__tests__/settings.services.test.ts +++ b/massmailing/src/main/resources/public/ts/services/__tests__/settings.services.test.ts @@ -1,5 +1,10 @@ -import MockAdapter from "axios-mock-adapter"; -import axios from "axios"; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {settingsService, Template} from "@massmailing/services"; import {MailTemplateCategory} from "@common/core/enum/mail-template-category"; @@ -8,61 +13,53 @@ describe('SettingsService', () => { const structureId: string = 'structureId'; const type = "MAIL" const category = "category" - const mock = new MockAdapter(axios); const data = {response: true}; - - mock.onGet(`/massmailing/settings/templates/${type}?structure=${structureId}&category=${category}`) - .reply(200, data); - + const url = `/massmailing/settings/templates/${type}?structure=${structureId}&category=${category}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); settingsService.get("MAIL", "structureId", "category").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('test of the proper functioning of the create method', done => { - const mock = new MockAdapter(axios); const data = {response: true}; const template: Template = {category: MailTemplateCategory.ALL, content: "", name: "", id: 4}; - - mock.onPost(`/massmailing/settings/templates`, template) - .reply(200, data); - + const url = `/massmailing/settings/templates`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'post'})); settingsService.create(template).then(response => { + expect(http.post).toHaveBeenCalledWith(url, template); expect(response).toEqual(data); done(); }); }); it('test of the proper functioning of the update method', done => { - const mock = new MockAdapter(axios); const data = {response: true}; const template: Template = {category: MailTemplateCategory.ALL, content: "", name: "", id: 4}; - - mock.onPut(`/massmailing/settings/templates/${template.id}`, template) - .reply(200, data); - + const url = `/massmailing/settings/templates/${template.id}`; + (http.put as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'put'})); settingsService.update(template).then(response => { + expect(http.put).toHaveBeenCalledWith(url, template); expect(response).toEqual(data); done(); }); }); it('test of the proper functioning of the delete method', done => { - const mock = new MockAdapter(axios); const data = {response: true}; const template: Template = {category: MailTemplateCategory.ALL, content: "", name: "", id: 4}; - - mock.onDelete(`/massmailing/settings/templates/${template.id}`) - .reply(200, data); - + const url = `/massmailing/settings/templates/${template.id}`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'delete'})); settingsService.delete(template).then(response => { + expect(http.delete).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); -}); \ No newline at end of file +}); diff --git a/package.json b/package.json index 7dcfb33d4..e16d437da 100644 --- a/package.json +++ b/package.json @@ -37,7 +37,6 @@ "entcore": "dev", "@screeb/sdk-browser": "0.7.0", "awesome-typescript-loader": "3.2.1", - "axios": "0.16.2", "core-js": "2.4.1", "gulp": "3.9.1", "gulp-clean": "^0.3.2", @@ -48,7 +47,7 @@ "webpack": "3.1.0", "webpack-stream": "3.2.0", "yargs": "^8.0.2", - "entcore-toolkit": "^1.0.1", + "entcore-toolkit": "2.0.0-dev.1", "tsconfig-paths-webpack-plugin": "^3.2.0", "apexcharts": "^3.26.0" }, @@ -65,7 +64,6 @@ "@types/jest": "^27.5.2", "@types/jquery": "^2.0.34", "angular-mocks": "^1.8.2", - "axios-mock-adapter": "^1.19.0", "gulp-replace": "^1.0.0", "jest": "26.6.3", "moment": "^2.21.0", diff --git a/pom.xml b/pom.xml index 10db5f0c3..aa8ec1d2c 100644 --- a/pom.xml +++ b/pom.xml @@ -38,13 +38,13 @@ statistics-presences - 2.2-SNAPSHOT + 2.2-develop-axios-SNAPSHOT 2.0.0-final 5.1.0 3.0-SNAPSHOT 2.0.2 [2.0,3.0) - 6.16-SNAPSHOT + 6.16-develop-axios-SNAPSHOT 0.10.2 2.2.2 4.2-SNAPSHOT diff --git a/presences/src/main/resources/public/ts/controllers/registers.ts b/presences/src/main/resources/public/ts/controllers/registers.ts index c1cdbe01a..0cad7af9e 100644 --- a/presences/src/main/resources/public/ts/controllers/registers.ts +++ b/presences/src/main/resources/public/ts/controllers/registers.ts @@ -31,7 +31,7 @@ import { } from '@common/utils'; import rights from '../rights'; import {Scope} from './main'; -import http, {AxiosError} from 'axios'; +import { http, HttpError } from 'entcore-toolkit'; import {EventsUtils, RegisterUtils, StudentsSearch} from '../utilities'; import {Reason} from '@presences/models/Reason'; import {SNIPLET_FORM_EMIT_EVENTS, SNIPLET_FORM_EVENTS} from '@common/model'; @@ -741,7 +741,7 @@ export const registersController = ng.controller('RegistersController', } else { let reason_id: number = events.reason_id; student.lateness = undefined; - await vm.toggleLateness(student).catch((err: AxiosError) => console.error(err)); + await vm.toggleLateness(student).catch((err: HttpError) => console.error(err)); if (typeof student.lateness.register_id === 'string') { student.lateness.register_id = parseInt(student.lateness.register_id); } diff --git a/presences/src/main/resources/public/ts/controllers/widgets/day-course.ts b/presences/src/main/resources/public/ts/controllers/widgets/day-course.ts index 283c7ef77..749a70170 100644 --- a/presences/src/main/resources/public/ts/controllers/widgets/day-course.ts +++ b/presences/src/main/resources/public/ts/controllers/widgets/day-course.ts @@ -2,7 +2,7 @@ import {Me, model, moment, ng, notify, idiom as lang} from 'entcore'; import {CourseUtils, DateUtils, PreferencesUtils, PresencesPreferenceUtils} from '@common/utils'; import {Course, Courses, Register, RegisterStatus} from '../../models'; import {RegisterUtils} from '../../utilities'; -import http from 'axios'; +import { http } from 'entcore-toolkit'; import rights from '../../rights'; import {Setting, settingService} from '../../services'; diff --git a/presences/src/main/resources/public/ts/controllers/widgets/side-register.ts b/presences/src/main/resources/public/ts/controllers/widgets/side-register.ts index a8f773d18..d07704d14 100644 --- a/presences/src/main/resources/public/ts/controllers/widgets/side-register.ts +++ b/presences/src/main/resources/public/ts/controllers/widgets/side-register.ts @@ -6,7 +6,7 @@ import {RegisterUtils} from '../../utilities'; import {COURSE_EVENTS} from '@common/model'; import {IAngularEvent} from 'angular'; import {Setting, settingService} from '../../services'; -import http, {AxiosResponse} from "axios"; +import { http, HttpResponse } from 'entcore-toolkit'; interface ViewModel { courses: Courses; @@ -154,7 +154,7 @@ export const sideRegisterController = ng.controller('SideRegisterController', [' } async function getPreference(): Promise { - let response: AxiosResponse = await http.get(`userbook/preference/presences.register`); + let response: HttpResponse = await http.get(`userbook/preference/presences.register`); if (response.status === 200 || response.status === 201) { return JSON.parse(response.data.preference); } else { diff --git a/presences/src/main/resources/public/ts/directives/statements-absence-form.ts b/presences/src/main/resources/public/ts/directives/statements-absence-form.ts index befa0b0a3..beb5a6ede 100644 --- a/presences/src/main/resources/public/ts/directives/statements-absence-form.ts +++ b/presences/src/main/resources/public/ts/directives/statements-absence-form.ts @@ -3,7 +3,7 @@ import {Student} from "@common/model/Student"; import {ISchoolYearPeriod, IStructureSlot, TimeSlotHourPeriod} from "@common/model"; import {IStatementAbsenceBody, IStatementsAbsences, IStatementsAbsencesRequest, StatementsAbsences} from "../models"; import {DateUtils} from "@common/utils"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import { IStatementsAbsencesService, IViescolaireService, @@ -265,7 +265,7 @@ export const StatementsAbsenceForm = ng.directive('statementsAbsenceForm', toasts.warning(lang.translate('presences.invalid.form')); return; } - let response: AxiosResponse = await statementsAbsencesService.create(form); + let response: HttpResponse = await statementsAbsencesService.create(form); if (response.status == 200 || response.status == 201) { toasts.confirm(lang.translate('presences.statement.form.create.success')); vm.form.description = ""; diff --git a/presences/src/main/resources/public/ts/models/CounsellorAbsence.ts b/presences/src/main/resources/public/ts/models/CounsellorAbsence.ts index 0be11a169..92299a7bf 100644 --- a/presences/src/main/resources/public/ts/models/CounsellorAbsence.ts +++ b/presences/src/main/resources/public/ts/models/CounsellorAbsence.ts @@ -1,4 +1,4 @@ -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {model, notify, toasts} from 'entcore'; declare let window: any; diff --git a/presences/src/main/resources/public/ts/models/Course.ts b/presences/src/main/resources/public/ts/models/Course.ts index 256a6eed6..f9d05396e 100644 --- a/presences/src/main/resources/public/ts/models/Course.ts +++ b/presences/src/main/resources/public/ts/models/Course.ts @@ -1,6 +1,5 @@ -import http, {AxiosResponse} from 'axios'; +import {Mix, http, HttpResponse} from 'entcore-toolkit'; import {_, moment} from 'entcore'; -import {Mix} from 'entcore-toolkit'; import {LoadingCollection} from '@common/model/LoadingCollection' import {DateUtils} from '@common/utils' import {ISubject} from "../models/Subject"; @@ -75,7 +74,7 @@ export class Courses extends LoadingCollection { const isSearchTeacher: string = (searchTeacher != null) ? `&searchTeacher=${searchTeacher}` : ''; const urlParams: string = `${forgottenRegisterParam}${multipleSlotParam}${startTimeParam}${endTimeParam}` +`${limitParam}${offsetParam}${orderParam}${isSearchTeacher}`; - const {data}: AxiosResponse = await http.get( + const {data}: HttpResponse = await http.get( `/presences/courses?${teacherFilter}${groupFilter}structure=${structure}&start=${start}&end=${end}${urlParams}` ); const newCourses = Mix.castArrayAs(Course, data); diff --git a/presences/src/main/resources/public/ts/models/Event/Event.ts b/presences/src/main/resources/public/ts/models/Event/Event.ts index 93bd2569c..4bb59c3ab 100644 --- a/presences/src/main/resources/public/ts/models/Event/Event.ts +++ b/presences/src/main/resources/public/ts/models/Event/Event.ts @@ -1,4 +1,4 @@ -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {moment, toasts} from 'entcore'; import {DateUtils} from '@common/utils'; import {EventType, LoadingCollection} from '@common/model'; @@ -155,7 +155,7 @@ export class Event { } } - async save(): Promise { + async save(): Promise { if (this.id) { return this.update(); } else { @@ -163,7 +163,7 @@ export class Event { } } - async update(): Promise { + async update(): Promise { try { if (this.type_id === EventType.DEPARTURE) { this.start_date = moment(this.start_date_time).format(DateUtils.FORMAT["YEAR-MONTH-DAY-HOUR-MIN-SEC"]); @@ -177,7 +177,7 @@ export class Event { return; } - async create(): Promise { + async create(): Promise { try { const {data} = await http.post('/presences/events', this.toJson()); this.id = data.id; @@ -188,7 +188,7 @@ export class Event { return; } - async delete(): Promise { + async delete(): Promise { try { await http.delete(`/presences/events/${this.id}`); } catch (err) { @@ -350,7 +350,7 @@ export class Absence extends Event { }; } - async getAbsence(absenceId: number): Promise { + async getAbsence(absenceId: number): Promise { try { return await http.get(`/presences/absence/${absenceId}`); } catch (err) { @@ -358,7 +358,7 @@ export class Absence extends Event { } } - async createAbsence(structureId?: string, reasonId?: number, ownerId?: string): Promise { + async createAbsence(structureId?: string, reasonId?: number, ownerId?: string): Promise { try { return await http.post('/presences/absence', this.toAbsenceJson(structureId, reasonId, ownerId)); } catch (err) { @@ -366,7 +366,7 @@ export class Absence extends Event { } } - async updateAbsence(absenceId?: number, structureId?: string, reasonId?: number, ownerId?: string): Promise { + async updateAbsence(absenceId?: number, structureId?: string, reasonId?: number, ownerId?: string): Promise { try { return await http.put(`/presences/absence/${absenceId}`, this.toAbsenceJson(structureId, reasonId, ownerId)); } catch (err) { @@ -392,7 +392,7 @@ export class Absence extends Event { } } - async deleteAbsence(absenceId?: number): Promise { + async deleteAbsence(absenceId?: number): Promise { try { return await http.delete(`/presences/absence/${absenceId}`); } catch (err) { @@ -400,7 +400,7 @@ export class Absence extends Event { } } - async deleteEventAbsence(eventId?: number): Promise { + async deleteEventAbsence(eventId?: number): Promise { try { return await http.delete(`/presences/events/${eventId}`); } catch (err) { diff --git a/presences/src/main/resources/public/ts/models/Exemption.ts b/presences/src/main/resources/public/ts/models/Exemption.ts index 85c8a44a6..df390c2aa 100644 --- a/presences/src/main/resources/public/ts/models/Exemption.ts +++ b/presences/src/main/resources/public/ts/models/Exemption.ts @@ -1,5 +1,4 @@ -import http from 'axios'; -import {Mix} from 'entcore-toolkit'; +import {Mix, http} from 'entcore-toolkit'; import {DateUtils} from "@common/utils"; import {ITimeSlot, LoadingCollection} from "@common/model"; import {_, moment} from "entcore"; diff --git a/presences/src/main/resources/public/ts/models/Register.ts b/presences/src/main/resources/public/ts/models/Register.ts index 69ceab229..a7b4195a1 100644 --- a/presences/src/main/resources/public/ts/models/Register.ts +++ b/presences/src/main/resources/public/ts/models/Register.ts @@ -1,6 +1,5 @@ -import http, {AxiosError, AxiosResponse} from 'axios'; +import {Mix, http, HttpError, HttpResponse} from 'entcore-toolkit'; import {_, moment, toasts} from 'entcore'; -import {Mix} from 'entcore-toolkit'; import {Event, EventType, ExemptionRegister, RegisterStatus, Remark} from './index'; import {LoadingCollection} from '@common/model'; import {registerService} from '../services'; @@ -159,13 +158,13 @@ export class Register extends LoadingCollection { const state_idOld = this.state_id; this.state_id = state_id; await registerService.setStatus(this.id, this.state_id) - .then((response: AxiosResponse) => { + .then((response: HttpResponse) => { // Prevent displaying toasts when selecting students in register. if (state_id === RegisterStatus.DONE) { toasts.confirm('presences.register.validation.success'); } }) - .catch((_: AxiosError) => { + .catch((_: HttpError) => { this.state_id = state_idOld; toasts.warning('presences.register.validation.error'); }); diff --git a/presences/src/main/resources/public/ts/models/Subject.ts b/presences/src/main/resources/public/ts/models/Subject.ts index ad5cf92bf..a95758278 100644 --- a/presences/src/main/resources/public/ts/models/Subject.ts +++ b/presences/src/main/resources/public/ts/models/Subject.ts @@ -1,5 +1,5 @@ import {_, notify} from 'entcore'; -import http from 'axios'; +import { http } from 'entcore-toolkit'; export interface ISubject { id?: string; diff --git a/presences/src/main/resources/public/ts/services/AbsenceService.ts b/presences/src/main/resources/public/ts/services/AbsenceService.ts index b93f8f81c..55bacff8a 100644 --- a/presences/src/main/resources/public/ts/services/AbsenceService.ts +++ b/presences/src/main/resources/public/ts/services/AbsenceService.ts @@ -1,6 +1,5 @@ import {ng, notify} from 'entcore'; -import {Mix} from 'entcore-toolkit'; -import http, {AxiosResponse} from 'axios'; +import {Mix, http, HttpResponse} from 'entcore-toolkit'; import {Absence, CounsellorAbsence} from '../models'; import {EXPORT_TYPE, ExportType} from "@common/core/enum/export-type.enum"; import {EventAbsenceSummary} from "@presences/models/Event/EventAbsenceSummary"; @@ -12,8 +11,8 @@ export interface AbsenceService { getAbsence(structure: string, students: Array, groups: Array, start: string, end: string, justified: boolean, regularized: boolean, reasons: Array): Promise>; getCounsellorAbsence(structure: string, students: string[], groups: string[], start: string, end: string, justified: boolean, regularized: boolean, reasons: number[]): Promise; - updateFollowed(ids: number[], followed: boolean): Promise; - regularizeAbsences(ids: Array, regularized: boolean): Promise; + updateFollowed(ids: number[], followed: boolean): Promise; + regularizeAbsences(ids: Array, regularized: boolean): Promise; export(exportType: ExportType, structureId: string, startDate: string, endDate: string, studentIds: Array, audienceIds: Array, regularized: boolean, followed: boolean, reasons: Array, noReason: boolean, halfBoarder: boolean, internal: boolean): void; @@ -29,7 +28,7 @@ async function retrieve(structure: string, students: Array, groups: Arra followed, halfBoarder, internal); if (page || page === 0) url += `&page=${page}`; - const {data}: AxiosResponse = await http.get(url); + const {data}: HttpResponse = await http.get(url); return data; } catch (err) { throw err; @@ -75,11 +74,11 @@ export const absenceService: AbsenceService = { justified, regularized, reasons)).filter((absence: CounsellorAbsence) => absence.student.name != null); }, - async updateFollowed(ids: number[], followed: boolean): Promise { + async updateFollowed(ids: number[], followed: boolean): Promise { return http.put(`/presences/absences/follow`, {absenceIds: ids, followed: followed}); }, - async regularizeAbsences(ids: Array, regularized: boolean): Promise { + async regularizeAbsences(ids: Array, regularized: boolean): Promise { if (ids.length === 0) return; try { await http.put(`/presences/absence/regularized`, {ids: ids, regularized: regularized}); @@ -127,7 +126,7 @@ export const absenceService: AbsenceService = { url += `?startAt=${startAt}&endAt=${endAt}`; } - const {data}: AxiosResponse = await http.get(url); + const {data}: HttpResponse = await http.get(url); return data; } catch (err) { throw err; diff --git a/presences/src/main/resources/public/ts/services/ActionService.ts b/presences/src/main/resources/public/ts/services/ActionService.ts index 0a09ec7ed..08e6fa2eb 100644 --- a/presences/src/main/resources/public/ts/services/ActionService.ts +++ b/presences/src/main/resources/public/ts/services/ActionService.ts @@ -1,16 +1,16 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {Action, ActionRequest} from "../models/Action"; export interface ActionService { getActions(structureId: string): Promise; // Settings - create(actionBody: ActionRequest): Promise; + create(actionBody: ActionRequest): Promise; - update(actionBody: ActionRequest): Promise; + update(actionBody: ActionRequest): Promise; - delete(actionId: number): Promise; + delete(actionId: number): Promise; } export const actionService: ActionService = { @@ -24,15 +24,15 @@ export const actionService: ActionService = { }, // Settings - create: (actionBody: ActionRequest): Promise => { + create: (actionBody: ActionRequest): Promise => { return http.post(`/presences/action`, actionBody); }, - update: (actionBody: ActionRequest): Promise => { + update: (actionBody: ActionRequest): Promise => { return http.put(`/presences/action`, actionBody); }, - delete: (actionId: number): Promise => { + delete: (actionId: number): Promise => { return http.delete(`/presences/action?id=${actionId}`); } }; diff --git a/presences/src/main/resources/public/ts/services/AlertService.ts b/presences/src/main/resources/public/ts/services/AlertService.ts index 6ad143038..e9cf551c3 100644 --- a/presences/src/main/resources/public/ts/services/AlertService.ts +++ b/presences/src/main/resources/public/ts/services/AlertService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {Alert, DeleteAlertRequest, InfiniteScrollAlert, StudentAlert} from "@presences/models/Alert"; export interface AlertService { @@ -11,7 +11,7 @@ export interface AlertService { reset(structureId: string, body: DeleteAlertRequest): Promise; - resetStudentAlertsCount(structureId: string, studentId: string, type: string): Promise; + resetStudentAlertsCount(structureId: string, studentId: string, type: string): Promise; exportCSV(structureId: string, type: string[]): void; } @@ -77,7 +77,7 @@ export const alertService: AlertService = { } }, - resetStudentAlertsCount(structureId: string, studentId: string, type: string): Promise { + resetStudentAlertsCount(structureId: string, studentId: string, type: string): Promise { return http.delete(`/presences/structures/${structureId}/students/${studentId}/alerts/reset?type=${type}`); }, diff --git a/presences/src/main/resources/public/ts/services/CalendarService.ts b/presences/src/main/resources/public/ts/services/CalendarService.ts index b28d44584..2f44a44b9 100644 --- a/presences/src/main/resources/public/ts/services/CalendarService.ts +++ b/presences/src/main/resources/public/ts/services/CalendarService.ts @@ -1,5 +1,5 @@ import {moment, ng} from 'entcore' -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {Absence, EventType, PresenceRequest, Presences} from '../models'; import {IPunishment} from '@incidents/models'; import {User} from '@common/model/User' diff --git a/presences/src/main/resources/public/ts/services/CollectiveAbsenceService.ts b/presences/src/main/resources/public/ts/services/CollectiveAbsenceService.ts index 082e1eace..0f47914e4 100644 --- a/presences/src/main/resources/public/ts/services/CollectiveAbsenceService.ts +++ b/presences/src/main/resources/public/ts/services/CollectiveAbsenceService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import { ICollectiveAbsence, ICollectiveAbsenceBody, ICollectiveAbsencesResponse, @@ -12,13 +12,13 @@ export interface CollectiveAbsenceService { getCollectiveAbsences(structureId: string, params: ICollectiveAbsenceBody): Promise; - createCollectiveAbsence(structureId: string, collectiveAbsence: ICollectiveAbsence): Promise; + createCollectiveAbsence(structureId: string, collectiveAbsence: ICollectiveAbsence): Promise; - updateCollectiveAbsence(structureId: string, collectiveAbsence: ICollectiveAbsence): Promise; + updateCollectiveAbsence(structureId: string, collectiveAbsence: ICollectiveAbsence): Promise; - removeAbsenceFromCollectiveAbsence(structureId: string, collectiveId: number, studentIds: Array): Promise; + removeAbsenceFromCollectiveAbsence(structureId: string, collectiveId: number, studentIds: Array): Promise; - deleteCollectiveAbsence(structureId: string, collectiveId: number): Promise; + deleteCollectiveAbsence(structureId: string, collectiveId: number): Promise; exportCollectiveAbsences(structureId: string, startDate: string, endDate: string): void; @@ -35,7 +35,7 @@ export const collectiveAbsenceService: CollectiveAbsenceService = { getCollectiveAbsence : async (structureId: string, collectiveId: number): Promise => { return http.get(`/presences/structures/${structureId}/absences/collectives/${collectiveId}`) - .then((res: AxiosResponse) => { return res.data; }); + .then((res: HttpResponse) => { return res.data; }); }, /** @@ -55,7 +55,7 @@ export const collectiveAbsenceService: CollectiveAbsenceService = { urlParams += (params.page !== undefined && params.page !== null) ? `&page=${params.page}` : ''; return http.get(`/presences/structures/${structureId}/absences/collectives${urlParams}`) - .then((res: AxiosResponse) => { + .then((res: HttpResponse) => { return res.data; }); }, @@ -65,7 +65,7 @@ export const collectiveAbsenceService: CollectiveAbsenceService = { * @param structureId structure identifier * @param collectiveAbsence collective absence to create */ - createCollectiveAbsence : async (structureId: string, collectiveAbsence: ICollectiveAbsence): Promise => { + createCollectiveAbsence : async (structureId: string, collectiveAbsence: ICollectiveAbsence): Promise => { return http.post(`/presences/structures/${structureId}/absences/collectives`, collectiveAbsence); }, @@ -74,7 +74,7 @@ export const collectiveAbsenceService: CollectiveAbsenceService = { * @param structureId structure identifier * @param collectiveAbsence collective absence to update */ - updateCollectiveAbsence : async (structureId: string, collectiveAbsence: ICollectiveAbsence): Promise => { + updateCollectiveAbsence : async (structureId: string, collectiveAbsence: ICollectiveAbsence): Promise => { return http.put(`/presences/structures/${structureId}/absences/collectives/${collectiveAbsence.id}`, collectiveAbsence); }, @@ -84,7 +84,7 @@ export const collectiveAbsenceService: CollectiveAbsenceService = { * @param collectiveId collective absence identifier * @param studentIds list of student identifiers */ - removeAbsenceFromCollectiveAbsence : async (structureId: string, collectiveId: number, studentIds: Array): Promise => { + removeAbsenceFromCollectiveAbsence : async (structureId: string, collectiveId: number, studentIds: Array): Promise => { const students: {studentIds: Array} = { studentIds: studentIds }; @@ -97,7 +97,7 @@ export const collectiveAbsenceService: CollectiveAbsenceService = { * @param structureId structure identifier * @param collectiveId collective absence identifier */ - deleteCollectiveAbsence : async (structureId: string, collectiveId: number): Promise => { + deleteCollectiveAbsence : async (structureId: string, collectiveId: number): Promise => { return http.delete(`/presences/structures/${structureId}/absences/collectives/${collectiveId}`); }, @@ -118,7 +118,7 @@ export const collectiveAbsenceService: CollectiveAbsenceService = { */ getStudentsAbsencesStatus : async (structureId: string, body: ICollectiveAbsenceBody): Promise> => { return http.post(`/presences/structures/${structureId}/absences/isAbsent`, body) - .then((res: AxiosResponse) => { return res.data.all; }); + .then((res: HttpResponse) => { return res.data.all; }); } }; diff --git a/presences/src/main/resources/public/ts/services/DisciplineService.ts b/presences/src/main/resources/public/ts/services/DisciplineService.ts index b666140b2..559cdfd71 100644 --- a/presences/src/main/resources/public/ts/services/DisciplineService.ts +++ b/presences/src/main/resources/public/ts/services/DisciplineService.ts @@ -1,15 +1,15 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {Discipline, DisciplineRequest} from "../models"; export interface DisciplineService { get(structureId: string): Promise; - create(disciplineBody: DisciplineRequest): Promise; + create(disciplineBody: DisciplineRequest): Promise; - update(disciplineBody: DisciplineRequest): Promise; + update(disciplineBody: DisciplineRequest): Promise; - delete(disciplineId: number): Promise; + delete(disciplineId: number): Promise; } export const disciplineService: DisciplineService = { @@ -22,15 +22,15 @@ export const disciplineService: DisciplineService = { } }, - create: async (disciplineBody: DisciplineRequest): Promise => { + create: async (disciplineBody: DisciplineRequest): Promise => { return http.post(`/presences/discipline`, disciplineBody); }, - update: async (disciplineBody: DisciplineRequest): Promise => { + update: async (disciplineBody: DisciplineRequest): Promise => { return http.put(`/presences/discipline`, disciplineBody); }, - delete: async (disciplineId: number): Promise => { + delete: async (disciplineId: number): Promise => { return http.delete(`/presences/discipline?id=${disciplineId}`); }, }; diff --git a/presences/src/main/resources/public/ts/services/EventService.ts b/presences/src/main/resources/public/ts/services/EventService.ts index b76a89ff5..3de47a7e5 100644 --- a/presences/src/main/resources/public/ts/services/EventService.ts +++ b/presences/src/main/resources/public/ts/services/EventService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {ActionBody, EventResponse, Events, IEventBody, IStudentEventRequest, IStudentEventResponse} from '../models'; import {DateUtils} from '@common/utils'; import {EventAbsenceSummary} from '@presences/models/Event/EventAbsenceSummary'; @@ -10,11 +10,11 @@ export interface EventService { getEventActions(event_id: number): Promise; - createAction(actionBody: ActionBody): Promise; + createAction(actionBody: ActionBody): Promise; getStudentEvent(studentEventRequest: IStudentEventRequest): Promise; - export(eventRequest: EventRequest, exportType: ExportType): Promise; + export(eventRequest: EventRequest, exportType: ExportType): Promise; getExportRequest(eventRequest: EventRequest, exportType: ExportType): string; @@ -22,11 +22,11 @@ export interface EventService { getAbsentsCounts(structureId: string, startDate: string, endDate: string): Promise; - createLatenessEvent(eventBody: IEventBody, structureId: string): Promise; + createLatenessEvent(eventBody: IEventBody, structureId: string): Promise; - updateEvent(eventId: number, eventBody: IEventBody): Promise; + updateEvent(eventId: number, eventBody: IEventBody): Promise; - deleteEvent(eventId: number): Promise; + deleteEvent(eventId: number): Promise; } export interface EventRequest { @@ -87,7 +87,7 @@ export const eventService: EventService = { const urlParams: string = `${structureId}${startDate}${endDate}${startTime}${endTime}${noReason}${noReasonLateness}` + `${eventType}${listReasonIds}${userId}${userIds}${classes}${classesIds}${regularized}${followed}${page}`; - const {data}: AxiosResponse = await http.get(`/presences/events${urlParams}`); + const {data}: HttpResponse = await http.get(`/presences/events${urlParams}`); return { pageCount: data.page_count, @@ -108,7 +108,7 @@ export const eventService: EventService = { } }, - createAction: async (actionBody: ActionBody): Promise => { + createAction: async (actionBody: ActionBody): Promise => { return http.post(`/presences/events/actions`, actionBody); }, @@ -143,9 +143,9 @@ export const eventService: EventService = { } }, - async export(eventRequest: EventRequest, exportType: ExportType): Promise { + async export(eventRequest: EventRequest, exportType: ExportType): Promise { try { - const {data}: AxiosResponse = await http.get(this.getExportRequest(eventRequest, exportType)); + const {data}: HttpResponse = await http.get(this.getExportRequest(eventRequest, exportType)); return data; } catch (err) { throw err; @@ -197,7 +197,7 @@ export const eventService: EventService = { && (eventRequest.followed === !eventRequest.notFollowed) ? `&followed=${eventRequest.followed}` : ''; const request: string = `${url}${structureId}${startDate}${endDate}${noReason}${noReasonLateness}${eventType}${listReasonIds}${userId}${classes}${regularized}${followed}`; - const {data}: AxiosResponse = await http.get(request); + const {data}: HttpResponse = await http.get(request); return data; } catch (err) { throw err; @@ -225,7 +225,7 @@ export const eventService: EventService = { url += `&startAt=${startDate}&endAt=${endDate}`; } - const {data}: AxiosResponse = await http.get(url); + const {data}: HttpResponse = await http.get(url); return data; } catch (err) { throw err; @@ -238,7 +238,7 @@ export const eventService: EventService = { * @param eventBody eventBody * @param structureId structure identifier */ - createLatenessEvent(eventBody: IEventBody, structureId: string): Promise { + createLatenessEvent(eventBody: IEventBody, structureId: string): Promise { return http.post(`/presences/events/${structureId}/lateness`, eventBody); }, @@ -248,7 +248,7 @@ export const eventService: EventService = { * @param eventId event identifier * @param eventBody eventBody */ - updateEvent(eventId: number, eventBody: IEventBody): Promise { + updateEvent(eventId: number, eventBody: IEventBody): Promise { return http.put(`/presences/events/${eventId}`, eventBody); }, @@ -257,7 +257,7 @@ export const eventService: EventService = { * * @param eventId event identifier */ - deleteEvent(eventId: number): Promise { + deleteEvent(eventId: number): Promise { return http.delete(`/presences/events/${eventId}`); } }; diff --git a/presences/src/main/resources/public/ts/services/ForgottenNotebookService.ts b/presences/src/main/resources/public/ts/services/ForgottenNotebookService.ts index 8f354b9a1..60e3044fd 100644 --- a/presences/src/main/resources/public/ts/services/ForgottenNotebookService.ts +++ b/presences/src/main/resources/public/ts/services/ForgottenNotebookService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {IForgottenNotebookResponse, IStudentEventRequest} from "../models"; export interface Notebook { @@ -21,11 +21,11 @@ export interface NotebookRequest { export interface ForgottenNotebookService { get(notebook: NotebookRequest): Promise; - create(notebook: NotebookRequest): Promise; + create(notebook: NotebookRequest): Promise; - update(notebookId: number, notebook: NotebookRequest): Promise; + update(notebookId: number, notebook: NotebookRequest): Promise; - delete(notebookId: number): Promise; + delete(notebookId: number): Promise; getStudentNotebooks(studentEventRequest: IStudentEventRequest): Promise; } @@ -41,15 +41,15 @@ export const forgottenNotebookService: ForgottenNotebookService = { } }, - create: async (notebook: NotebookRequest): Promise => { + create: async (notebook: NotebookRequest): Promise => { return await http.post(`/presences/forgotten/notebook`, notebook); }, - update: async (notebookId: number, notebook: NotebookRequest): Promise => { + update: async (notebookId: number, notebook: NotebookRequest): Promise => { return await http.put(`/presences/forgotten/notebook/${notebookId}`, {date: notebook.date}); }, - delete: async (notebookId: number): Promise => { + delete: async (notebookId: number): Promise => { return await http.delete(`/presences/forgotten/notebook/${notebookId}`); }, diff --git a/presences/src/main/resources/public/ts/services/MementoService.ts b/presences/src/main/resources/public/ts/services/MementoService.ts index a36fab784..0263b67bf 100644 --- a/presences/src/main/resources/public/ts/services/MementoService.ts +++ b/presences/src/main/resources/public/ts/services/MementoService.ts @@ -1,4 +1,4 @@ -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {IndicatorBody} from "@statistics/model/Indicator"; import {IMonthlyGraph} from "@statistics/model/Monthly"; import {GlobalResponse} from "@statistics/model/Global"; @@ -26,11 +26,11 @@ export interface IMementoService { export const MementoService: IMementoService = { async getStudentEventsSummaryGraph(structure: string, student: string, body: IndicatorBody): Promise { return http.post(`/presences/statistics/structures/${structure}/student/${student}/graph`, body) - .then((res: AxiosResponse) => (res.data)); + .then((res: HttpResponse) => (res.data)); }, async getStudentEventsSummary(structure: string, student: string, body: IndicatorBody): Promise { return http.post(`/presences/statistics/structures/${structure}/student/${student}`, body) - .then((res: AxiosResponse) => (res.data)); + .then((res: HttpResponse) => (res.data)); } } \ No newline at end of file diff --git a/presences/src/main/resources/public/ts/services/PeriodService.ts b/presences/src/main/resources/public/ts/services/PeriodService.ts index c73f9f0f9..61441cdbc 100644 --- a/presences/src/main/resources/public/ts/services/PeriodService.ts +++ b/presences/src/main/resources/public/ts/services/PeriodService.ts @@ -1,4 +1,4 @@ -import http from 'axios'; +import { http } from 'entcore-toolkit'; import {ng} from "entcore"; export interface IPeriod { diff --git a/presences/src/main/resources/public/ts/services/PresenceService.ts b/presences/src/main/resources/public/ts/services/PresenceService.ts index f7e4eec32..a1dc5e54b 100644 --- a/presences/src/main/resources/public/ts/services/PresenceService.ts +++ b/presences/src/main/resources/public/ts/services/PresenceService.ts @@ -1,15 +1,15 @@ import {ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {Presence, PresenceBody, PresenceRequest} from "../models"; export interface PresenceService { get(presenceRequest: PresenceRequest): Promise; - create(presenceBody: PresenceBody): Promise; + create(presenceBody: PresenceBody): Promise; - update(presenceBody: PresenceBody): Promise; + update(presenceBody: PresenceBody): Promise; - delete(presenceId: number): Promise; + delete(presenceId: number): Promise; exportCSV(punishmentRequest: PresenceRequest): Promise; @@ -46,22 +46,22 @@ function filterUrl(presenceRequest: PresenceRequest): string { export const presenceService: PresenceService = { get: async (presenceRequest: PresenceRequest): Promise => { try { - const {data}: AxiosResponse = await http.get(`/presences/presences${filterUrl(presenceRequest)}`); + const {data}: HttpResponse = await http.get(`/presences/presences${filterUrl(presenceRequest)}`); return data } catch (err) { throw err; } }, - create: async (presenceBody: PresenceBody): Promise => { + create: async (presenceBody: PresenceBody): Promise => { return http.post(`/presences/presence`, presenceBody); }, - update: async (presenceBody: PresenceBody): Promise => { + update: async (presenceBody: PresenceBody): Promise => { return http.put(`/presences/presence`, presenceBody); }, - delete: async (PresenceId: number): Promise => { + delete: async (PresenceId: number): Promise => { return http.delete(`/presences/presence?id=${PresenceId}`); }, diff --git a/presences/src/main/resources/public/ts/services/ReasonService.ts b/presences/src/main/resources/public/ts/services/ReasonService.ts index e456790a9..9578eafe0 100644 --- a/presences/src/main/resources/public/ts/services/ReasonService.ts +++ b/presences/src/main/resources/public/ts/services/ReasonService.ts @@ -1,16 +1,16 @@ import {idiom as lang, ng} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {Reason, ReasonRequest} from "@presences/models/Reason"; import {REASON_TYPE_ID} from "@common/core/enum/reason-type-id"; export interface ReasonService { getReasons(structureId: string, reasonTypeId?: Number): Promise; - create(reasonBody: ReasonRequest, reasonTypeId?: Number): Promise; + create(reasonBody: ReasonRequest, reasonTypeId?: Number): Promise; - update(reasonBody: ReasonRequest): Promise; + update(reasonBody: ReasonRequest): Promise; - delete(reasonId: number): Promise; + delete(reasonId: number): Promise; } export const reasonService: ReasonService = { @@ -30,16 +30,16 @@ export const reasonService: ReasonService = { } }, - create: async (reasonBody: ReasonRequest, reasonTypeId?: Number): Promise => { + create: async (reasonBody: ReasonRequest, reasonTypeId?: Number): Promise => { let reasonTypeIdParam: string = reasonTypeId ? `?reasonTypeId=${reasonTypeId}` : ''; return http.post(`/presences/reason${reasonTypeIdParam}`, reasonBody); }, - update: async (reasonBody: ReasonRequest): Promise => { + update: async (reasonBody: ReasonRequest): Promise => { return http.put(`/presences/reason`, reasonBody); }, - delete: async (reasonId: number): Promise => { + delete: async (reasonId: number): Promise => { return http.delete(`/presences/reason?id=${reasonId}`); }, }; diff --git a/presences/src/main/resources/public/ts/services/RegisterService.ts b/presences/src/main/resources/public/ts/services/RegisterService.ts index 563473695..b5fef3395 100644 --- a/presences/src/main/resources/public/ts/services/RegisterService.ts +++ b/presences/src/main/resources/public/ts/services/RegisterService.ts @@ -1,9 +1,9 @@ import {ng} from 'entcore'; -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {Course} from "@presences/models"; export interface RegisterService { - setStatus(registerId: number, state_id: number): Promise; + setStatus(registerId: number, state_id: number): Promise; getLastForgottenRegisterCourses(structureId: string, startDate: string, endDate: string, teacherIds?: Array, groupNames?: Array): Promise; @@ -11,7 +11,7 @@ export interface RegisterService { export const registerService: RegisterService = { - setStatus: async (registerId: number, state_id: number): Promise => { + setStatus: async (registerId: number, state_id: number): Promise => { return http.put(`/presences/registers/${registerId}/status`, {state_id}); }, @@ -31,7 +31,7 @@ export const registerService: RegisterService = { }) } - return http.get(`/presences/structures/${structureId}/registers/forgotten${urlParams}`).then((res: AxiosResponse) => { + return http.get(`/presences/structures/${structureId}/registers/forgotten${urlParams}`).then((res: HttpResponse) => { return res.data; }); } diff --git a/presences/src/main/resources/public/ts/services/RegistryService.ts b/presences/src/main/resources/public/ts/services/RegistryService.ts index e5c27ec26..ac9da2739 100644 --- a/presences/src/main/resources/public/ts/services/RegistryService.ts +++ b/presences/src/main/resources/public/ts/services/RegistryService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore' -import http from 'axios'; +import { http } from 'entcore-toolkit'; export interface Registry { id: string; diff --git a/presences/src/main/resources/public/ts/services/SettingsService.ts b/presences/src/main/resources/public/ts/services/SettingsService.ts index d4eee333c..f5b1616b9 100644 --- a/presences/src/main/resources/public/ts/services/SettingsService.ts +++ b/presences/src/main/resources/public/ts/services/SettingsService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; export interface Setting { alert_absence_threshold?: number @@ -40,7 +40,7 @@ export const settingService: SettingsService = { }, async retrieveMultipleSlotSetting(structureId: string): Promise { return http.get(`/presences/structures/${structureId}/settings/multiple-slots`) - .then((res: AxiosResponse) => res.data.allow_multiple_slots); + .then((res: HttpResponse) => res.data.allow_multiple_slots); } }; diff --git a/presences/src/main/resources/public/ts/services/StatementsAbsencesService.ts b/presences/src/main/resources/public/ts/services/StatementsAbsencesService.ts index 98d0b76ad..24e6ca902 100644 --- a/presences/src/main/resources/public/ts/services/StatementsAbsencesService.ts +++ b/presences/src/main/resources/public/ts/services/StatementsAbsencesService.ts @@ -1,5 +1,5 @@ import {ng} from 'entcore'; -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import { IStatementAbsenceBody, IStatementsAbsences, @@ -14,13 +14,13 @@ export interface IStatementsAbsencesService { download(statementsAbsencesBody: IStatementAbsenceBody): void; - create(statementsAbsencesBody: IStatementAbsenceBody): Promise; + create(statementsAbsencesBody: IStatementAbsenceBody): Promise; - update(statementsAbsencesId: number, statementsAbsencesBody: IStatementAbsenceBody): Promise; + update(statementsAbsencesId: number, statementsAbsencesBody: IStatementAbsenceBody): Promise; - validate(statementsAbsencesId: number, statementsAbsencesBody: IStatementAbsenceBody): Promise; + validate(statementsAbsencesId: number, statementsAbsencesBody: IStatementAbsenceBody): Promise; - delete(statementsAbsencesId: number): Promise; + delete(statementsAbsencesId: number): Promise; export(statementsAbsences: IStatementsAbsencesRequest): string; @@ -33,7 +33,7 @@ export const statementsAbsencesService: IStatementsAbsencesService = { get: async (statementsAbsences: IStatementsAbsencesRequest): Promise => { try { const urlParams: String = statementsAbsencesService.getUrl(statementsAbsences, statementsAbsences.page, statementsAbsences.limit, statementsAbsences.offset); - const {data}: AxiosResponse = await http.get(`${statementsAbsencesService.baseUrl}${urlParams}`); + const {data}: HttpResponse = await http.get(`${statementsAbsencesService.baseUrl}${urlParams}`); return data; } catch (err) { throw err; @@ -47,7 +47,7 @@ export const statementsAbsencesService: IStatementsAbsencesService = { window.open(`${basicUrl}${urlFetchingData}${structure_id}`); }, - create: async (statementsAbsences: IStatementAbsenceBody): Promise => { + create: async (statementsAbsences: IStatementAbsenceBody): Promise => { const formData: FormData = new FormData(); const headers = {'headers': {'Content-type': 'multipart/form-data'}}; @@ -61,15 +61,15 @@ export const statementsAbsencesService: IStatementsAbsencesService = { return http.post(`/presences/statements/absences${statementsAbsences.file ? '/attachment' : ''}`, formData, headers); }, - validate: async (statementsAbsencesId: number, {isTreated}: IStatementAbsenceBody): Promise => { + validate: async (statementsAbsencesId: number, {isTreated}: IStatementAbsenceBody): Promise => { return http.put(`${statementsAbsencesService.baseUrl}/${statementsAbsencesId}/validate`, {is_treated: isTreated}); }, - update: async (statementsAbsencesId: number, statementsAbsences: IStatementAbsenceBody): Promise => { + update: async (statementsAbsencesId: number, statementsAbsences: IStatementAbsenceBody): Promise => { return http.put(`${statementsAbsencesService.baseUrl}/${statementsAbsencesId}`, statementsAbsences); }, - delete: async (statementsAbsencesId: number): Promise => { + delete: async (statementsAbsencesId: number): Promise => { return http.delete(`${statementsAbsencesService.baseUrl}/${statementsAbsencesId}`); }, diff --git a/presences/src/main/resources/public/ts/services/__tests__/absence.service.test.ts b/presences/src/main/resources/public/ts/services/__tests__/absence.service.test.ts index c1cb469c8..b6a65ac1d 100644 --- a/presences/src/main/resources/public/ts/services/__tests__/absence.service.test.ts +++ b/presences/src/main/resources/public/ts/services/__tests__/absence.service.test.ts @@ -1,18 +1,23 @@ -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {absenceService} from "../AbsenceService"; describe('AbsenceService', () => { it('returns data when getAbsenceMarkers request is correctly called', done => { - const mock = new MockAdapter(axios); const structureId = 'structure'; const start = 'start'; const end = 'end'; const data = {response: true}; - mock.onGet(`/presences/structures/${structureId}/absences/markers?startAt=${start}&endAt=${end}`) - .reply(200, data); + const url = `/presences/structures/${structureId}/absences/markers?startAt=${start}&endAt=${end}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); absenceService.getAbsenceMarkers(structureId, start, end).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); diff --git a/presences/src/main/resources/public/ts/services/__tests__/alert.service.test.ts b/presences/src/main/resources/public/ts/services/__tests__/alert.service.test.ts index 0230d8251..bcaf358c9 100644 --- a/presences/src/main/resources/public/ts/services/__tests__/alert.service.test.ts +++ b/presences/src/main/resources/public/ts/services/__tests__/alert.service.test.ts @@ -1,11 +1,15 @@ -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {alertService} from "@presences/services"; import {DeleteAlertRequest, StudentAlert} from "@presences/models/Alert"; describe('AlertService', () => { it('returns data when reset request is correctly called', done => { - const mock = new MockAdapter(axios); const deleted_alert: Array = [{ student_id: "student_id", type: "type", @@ -20,30 +24,30 @@ describe('AlertService', () => { deleted_alert: deleted_alert }; const structure_id: string = "structure_id"; - mock.onDelete(`/presences/structures/structure_id/alerts`, {data: body}) - .reply(200, data); + const url = `/presences/structures/structure_id/alerts`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'delete'})); alertService.reset(structure_id, body).then(response => { + expect(http.delete).toHaveBeenCalledWith(url, {data: body}); expect(response).toEqual(data); done(); }); }); it('returns data when getAlerts request is correctly called', done => { - const mock = new MockAdapter(axios); const structureId: string = "structure_id"; const data = {response: true}; - mock.onGet(`/presences/structures/${structureId}/alerts/summary`) - .reply(200, data); + const url = `/presences/structures/${structureId}/alerts/summary`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); alertService.getAlerts(structureId).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('returns data when getStudentsAlerts request is correctly called', done => { - const mock = new MockAdapter(axios); const structureId: string = "structure_id"; const types: string[] = ["type1", "type2"]; const students: string[] = ["student1", "student2"]; @@ -51,40 +55,41 @@ describe('AlertService', () => { const start_at: string = "start_at"; const end_at: string = "end_at"; const data = {response: true}; - mock.onGet(`/presences/structures/structure_id/alerts?student=student1&student=student2&class=group1&class=group2&start_at=start_at&end_at=end_at&&type=type1&type=type2`) - .reply(200, data); + const url = `/presences/structures/structure_id/alerts?student=student1&student=student2&class=group1&class=group2&start_at=start_at&end_at=end_at&&type=type1&type=type2`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); alertService.getStudentsAlerts(structureId, types, students, groups, start_at, end_at).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('returns data when getStudentAlerts request is correctly called', done => { - const mock = new MockAdapter(axios); const structureId: string = "structure_id"; const studentId: string = "studentId"; const type: string = "type"; const data = {response: true}; - mock.onGet(`/presences/structures/${structureId}/students/${studentId}/alerts?type=${type}`) - .reply(200, data); + const url = `/presences/structures/${structureId}/students/${studentId}/alerts?type=${type}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); alertService.getStudentAlerts(structureId, studentId, type).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('returns data when resetStudentAlertsCount request is correctly called', done => { - const mock = new MockAdapter(axios); const structureId: string = "structure_id"; const studentId: string = "studentId"; const type: string = "type"; const data = {response: true}; - mock.onDelete(`/presences/structures/${structureId}/students/${studentId}/alerts/reset?type=${type}`) - .reply(200, data); + const url = `/presences/structures/${structureId}/students/${studentId}/alerts/reset?type=${type}`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'delete'})); alertService.resetStudentAlertsCount(structureId, studentId, type).then(response => { + expect(http.delete).toHaveBeenCalledWith(url); expect(response.data).toEqual(data); done(); }); diff --git a/presences/src/main/resources/public/ts/services/__tests__/event.service.test.ts b/presences/src/main/resources/public/ts/services/__tests__/event.service.test.ts index eaeca6ba8..5b2803dcb 100644 --- a/presences/src/main/resources/public/ts/services/__tests__/event.service.test.ts +++ b/presences/src/main/resources/public/ts/services/__tests__/event.service.test.ts @@ -1,12 +1,16 @@ -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {EventRequest, eventService} from "@presences/services"; import {ActionBody, IEventBody, IStudentEventRequest} from "@presences/models"; import {ExportType} from "@common/core/enum/export-type.enum"; describe('EventService', () => { it('check get methode in EventService', done => { - const mock = new MockAdapter(axios); const eventRequest : EventRequest = { classes: "classes1,classes2", classesIds: ["classesId1", "classesId2"], @@ -28,21 +32,21 @@ describe('EventService', () => { } const data = {all: [], page_count: 3}; const result = {all: [], events: [], pageCount: 3}; - mock.onGet(`/presences/events?structureId=${eventRequest.structureId}&startDate=${eventRequest.startDate}&endDate=${eventRequest.endDate}` + + const url = `/presences/events?structureId=${eventRequest.structureId}&startDate=${eventRequest.startDate}&endDate=${eventRequest.endDate}` + `&startTime=${eventRequest.startTime}&endTime=${eventRequest.endTime}&noReason=${eventRequest.noReason}&noReasonLateness=${eventRequest.noReasonLateness}` + `&eventType=${eventRequest.eventType}&reasonIds=${eventRequest.listReasonIds}&userId=${eventRequest.userId}&userId=${eventRequest.userIds[0]}` + `&userId=${eventRequest.userIds[1]}&classes=${eventRequest.classes}&classes=${eventRequest.classesIds[0]}&classes=${eventRequest.classesIds[1]}` + - `®ularized=${eventRequest.regularized}&page=${eventRequest.page}`) - .reply(200, data); + `®ularized=${eventRequest.regularized}&page=${eventRequest.page}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); eventService.get(eventRequest).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(result); done(); }); }); it('check get methode in EventService', done => { - const mock = new MockAdapter(axios); const eventRequest : EventRequest = { classes: "classes1,classes2", classesIds: ["classesId1", "classesId2"], @@ -64,50 +68,47 @@ describe('EventService', () => { } const data = {all: [], page_count: 3}; const result = {all: [], events: [], pageCount: 3}; - mock.onGet(`/presences/events?structureId=${eventRequest.structureId}&startDate=${eventRequest.startDate}&endDate=${eventRequest.endDate}` + + const url = `/presences/events?structureId=${eventRequest.structureId}&startDate=${eventRequest.startDate}&endDate=${eventRequest.endDate}` + `&startTime=${eventRequest.startTime}&endTime=${eventRequest.endTime}&noReason=${eventRequest.noReason}` + `&eventType=${eventRequest.eventType}&userId=${eventRequest.userId}&userId=${eventRequest.userIds[0]}` + `&userId=${eventRequest.userIds[1]}&classes=${eventRequest.classes}&classes=${eventRequest.classesIds[0]}&classes=${eventRequest.classesIds[1]}` + - `®ularized=${eventRequest.regularized}&followed=${!eventRequest.notFollowed}&page=${eventRequest.page}`) - .reply(200, data); + `®ularized=${eventRequest.regularized}&followed=${!eventRequest.notFollowed}&page=${eventRequest.page}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); eventService.get(eventRequest).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(result); done(); }); }); it('check getEventActions methode in EventService', done => { - const mock = new MockAdapter(axios); - const data = {response: true}; const eventId = 3; - mock.onGet(`/presences/events/${eventId}/actions`) - .reply(200, data); + const url = `/presences/events/${eventId}/actions`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); eventService.getEventActions(eventId).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('check createAction methode in EventService', done => { - const mock = new MockAdapter(axios); - const data = {response: true}; const actionBody : ActionBody = {actionId: 0, comment: "", eventId: [3], owner: ""}; - mock.onPost(`/presences/events/actions`, actionBody) - .reply(200, data); + const url = `/presences/events/actions`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'post'})); eventService.createAction(actionBody).then(response => { + expect(http.post).toHaveBeenCalledWith(url, actionBody); expect(response.data).toEqual(data); done(); }); }); it('check getStudentEvent methode in EventService', done => { - const mock = new MockAdapter(axios); - const data = {response: true}; let studentEventRequest : IStudentEventRequest = { end_at: "end_at", @@ -118,12 +119,13 @@ describe('EventService', () => { student_id: "student_id", type: ["1","3"] }; - mock.onGet(`/presences/students/student_id/events?structure_id=${studentEventRequest.structure_id}` + + let url = `/presences/students/student_id/events?structure_id=${studentEventRequest.structure_id}` + `&start_at=${studentEventRequest.start_at}&end_at=${studentEventRequest.end_at}&type=${studentEventRequest.type[0]}` + - `&type=${studentEventRequest.type[1]}&limit=${studentEventRequest.limit}&offset=${studentEventRequest.offset}`) - .reply(200, data); + `&type=${studentEventRequest.type[1]}&limit=${studentEventRequest.limit}&offset=${studentEventRequest.offset}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); eventService.getStudentEvent(studentEventRequest).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); @@ -138,19 +140,19 @@ describe('EventService', () => { type: ["1","3"] }; - mock.onGet(`/presences/students/student_id/events?structure_id=${studentEventRequest.structure_id}` + + url = `/presences/students/student_id/events?structure_id=${studentEventRequest.structure_id}` + `&start_at=${studentEventRequest.start_at}&end_at=${studentEventRequest.end_at}&type=${studentEventRequest.type[0]}` + - `&type=${studentEventRequest.type[1]}`) - .reply(200, data); + `&type=${studentEventRequest.type[1]}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); eventService.getStudentEvent(studentEventRequest).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('check export methode in EventService', done => { - const actionBody : ActionBody = {actionId: 0, comment: "", eventId: undefined, owner: ""}; const eventRequest : EventRequest = { classes: "classes1,classes2", classesIds: ["classesId1", "classesId2"], @@ -177,67 +179,59 @@ describe('EventService', () => { }); it('check getAbsentsCounts methode in EventService', done => { - const mock = new MockAdapter(axios); - const data = {response: true}; //Must find a way to mock currentdate const startDate: string = "startDate"; const endDate: string = "endDate"; - - mock.onGet(`/presences/events/absences/summary&startAt=${startDate}&endAt=${endDate}`) - .reply(200, data); + const url = `/presences/events/absences/summary&startAt=${startDate}&endAt=${endDate}`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); eventService.getAbsentsCounts(undefined, startDate, endDate).then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); }); it('check createLatenessEvent methode in EventService', done => { - const mock = new MockAdapter(axios); - const data = {response: true}; //Must find a way to mock currentdate const structureId: string = "structureId"; const eventBody: IEventBody = {end_date: "", reason_id: 0, register_id: 0, start_date: "", student_id: ""}; - - mock.onPost(`/presences/events/${structureId}/lateness`, eventBody) - .reply(200, data); + const url = `/presences/events/${structureId}/lateness`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'post'})); eventService.createLatenessEvent(eventBody, structureId).then(response => { + expect(http.post).toHaveBeenCalledWith(url, eventBody); expect(response.data).toEqual(data); done(); }); }); it('check updateEvent methode in EventService', done => { - const mock = new MockAdapter(axios); - const data = {response: true}; //Must find a way to mock currentdate const eventId = 3; const eventBody: IEventBody = {end_date: "", reason_id: 0, register_id: 0, start_date: "", student_id: ""}; - - mock.onPut(`/presences/events/${eventId}`, eventBody) - .reply(200, data); + const url = `/presences/events/${eventId}`; + (http.put as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'put'})); eventService.updateEvent(eventId, eventBody).then(response => { + expect(http.put).toHaveBeenCalledWith(url, eventBody); expect(response.data).toEqual(data); done(); }); }); it('check deleteEvent methode in EventService', done => { - const mock = new MockAdapter(axios); - const data = {response: true}; //Must find a way to mock currentdate const eventId = 3; - - mock.onDelete(`/presences/events/${eventId}`) - .reply(200, data); + const url = `/presences/events/${eventId}`; + (http.delete as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'delete'})); eventService.deleteEvent(eventId).then(response => { + expect(http.delete).toHaveBeenCalledWith(url); expect(response.data).toEqual(data); done(); }); diff --git a/presences/src/main/resources/public/ts/services/__tests__/memento.service.test.ts b/presences/src/main/resources/public/ts/services/__tests__/memento.service.test.ts index ffc55ffab..3a7efd602 100644 --- a/presences/src/main/resources/public/ts/services/__tests__/memento.service.test.ts +++ b/presences/src/main/resources/public/ts/services/__tests__/memento.service.test.ts @@ -1,5 +1,10 @@ -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {MementoService} from '../MementoService'; import {IndicatorBody} from "@statistics/model/Indicator"; import {GlobalResponse} from "@statistics/model/Global"; @@ -11,7 +16,6 @@ describe('MementoService', () => { const structure: string = 'structure'; const start: string = 'start'; const end: string = 'end'; - const mock = new MockAdapter(axios); const body: IndicatorBody = { start: start, end: end, @@ -29,27 +33,11 @@ describe('MementoService', () => { rate: {ABSENCE_TOTAL: 10}, slots: undefined }; - const regularized: Array = [{"2020-01": {count: 1}}]; - regularized.push({"2020-04": {count: 0}}); - const no_reason: Array = [{"2020-01": {count: 2}}]; - no_reason.push({"2020-04": {count: 20}}); - const lateness: Array = [{"2020-01": {count: 3}}]; - lateness.push({"2020-04": {count: 0}}); - const departure: Array = [{"2020-01": {count: 4}}]; - departure.push({"2020-04": {count: 0}}); - const dataGraph: IMonthlyGraph = { - data: { - REGULARIZED: regularized, - NO_REASON: no_reason, - LATENESS: lateness, - DEPARTURE: departure - }, - months: ["2020-01", "2020-04"] - }; - mock.onPost(`/presences/statistics/structures/${structure}/student/${student}`, body) - .reply(200, dataGlobal); + const url = `/presences/statistics/structures/${structure}/student/${student}`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGlobal, {url, method: 'post'})); MementoService.getStudentEventsSummary('structure', 'student', body).then(response => { + expect(http.post).toHaveBeenCalledWith(url, body); expect(response).toEqual(dataGlobal); done(); }); @@ -60,7 +48,6 @@ describe('MementoService', () => { const structure: string = 'structure'; const start: string = 'start'; const end: string = 'end'; - const mock = new MockAdapter(axios); const body: IndicatorBody = { start: start, end: end, @@ -72,12 +59,6 @@ describe('MementoService', () => { types: [], users: [student] } - const dataGlobal: GlobalResponse = { - count: undefined, - data: undefined, - rate: {ABSENCE_TOTAL: 10}, - slots: undefined - }; const regularized: Array = [{"2020-01": {count: 1}}]; regularized.push({"2020-04": {count: 0}}); const no_reason: Array = [{"2020-01": {count: 2}}]; @@ -95,11 +76,11 @@ describe('MementoService', () => { }, months: ["2020-01", "2020-04"] }; - - mock.onPost(`/presences/statistics/structures/${structure}/student/${student}/graph`, body) - .reply(200, dataGraph); + const url = `/presences/statistics/structures/${structure}/student/${student}/graph`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(dataGraph, {url, method: 'post'})); MementoService.getStudentEventsSummaryGraph('structure', 'student', body).then(response => { + expect(http.post).toHaveBeenCalledWith(url, body); expect(response).toEqual(dataGraph); done(); }); diff --git a/presences/src/main/resources/public/ts/services/__tests__/settings.service.test.ts b/presences/src/main/resources/public/ts/services/__tests__/settings.service.test.ts index aef3dbbb5..e1354098e 100644 --- a/presences/src/main/resources/public/ts/services/__tests__/settings.service.test.ts +++ b/presences/src/main/resources/public/ts/services/__tests__/settings.service.test.ts @@ -2,21 +2,24 @@ jest.mock('entcore', () => ({ ng: {service: jest.fn()} })) -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; import {Setting, settingService} from '../SettingsService'; describe('SettingsService', () => { it('returns data when retrieve request is correctly called', done => { const structureId: string = 'structureId'; - const mock = new MockAdapter(axios); const data = {response: true}; - - mock.onGet(`/presences/structures/${structureId}/settings`) - .reply(200, data); - + const url = `/presences/structures/${structureId}/settings`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); settingService.retrieve("structureId").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data); done(); }); @@ -25,14 +28,12 @@ describe('SettingsService', () => { it('returns data when retrieve multiple slot request is correctly called', done => { const structureId: string = 'structureId'; - const mock = new MockAdapter(axios); const data: Setting = {"allow_multiple_slots": true}; - - mock.onGet(`/presences/structures/${structureId}/settings/multiple-slots`) - .reply(200, data); - + const url = `/presences/structures/${structureId}/settings/multiple-slots`; + (http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url})); settingService.retrieveMultipleSlotSetting("structureId").then(response => { + expect(http.get).toHaveBeenCalledWith(url); expect(response).toEqual(data.allow_multiple_slots); done(); }); @@ -41,13 +42,12 @@ describe('SettingsService', () => { it('returns data when put request is correctly called', done => { const structureId: string = 'structureId'; - const mock = new MockAdapter(axios); const data = {response: true}; - - mock.onPut(`/presences/structures/${structureId}/settings`) - .reply(200, data); + const url = `/presences/structures/${structureId}/settings`; + (http.put as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'put'})); settingService.put("structureId", {}).then(response => { + expect(http.put).toHaveBeenCalledWith(url, {}); expect(response).toEqual(data); done(); }); diff --git a/presences/src/main/resources/public/ts/services/initialization.service.ts b/presences/src/main/resources/public/ts/services/initialization.service.ts index 6c43b7060..0dd2f7acc 100644 --- a/presences/src/main/resources/public/ts/services/initialization.service.ts +++ b/presences/src/main/resources/public/ts/services/initialization.service.ts @@ -1,5 +1,5 @@ import {ng, idiom} from 'entcore' -import http, {AxiosResponse} from 'axios'; +import { http, HttpResponse } from 'entcore-toolkit'; import {INIT_TYPE} from "../core/enum/init-type"; import { HOLIDAYS_ZONE, IInitFormZone, InitForm } from '../models/init-form.model'; @@ -18,8 +18,8 @@ export interface IInitService { getPresencesInitStatus(structureId: string): Promise; getViescoInitStatus(structureId: string): Promise; - initPresences(structureId: string, initType: INIT_TYPE): Promise; - initViesco(structureId: string, initType: INIT_TYPE, initForm: InitForm): Promise; + initPresences(structureId: string, initType: INIT_TYPE): Promise; + initViesco(structureId: string, initType: INIT_TYPE, initForm: InitForm): Promise; getTeachersInitializationStatus(structureId: string): Promise; getZones(): IInitFormZone[]; @@ -31,26 +31,26 @@ export const initService: IInitService = { getPresencesInitStatus: async (structureId: string): Promise => { return http.get(`/presences/initialization/structures/${structureId}`) - .then((res: AxiosResponse) => res.data.initialized); + .then((res: HttpResponse) => res.data.initialized); }, getViescoInitStatus: async (structureId: string): Promise => { return http.get(`/viescolaire/structures/${structureId}/initialization`) - .then((res: AxiosResponse) => res.data); + .then((res: HttpResponse) => res.data); }, - initPresences: async (structureId: string, initType: INIT_TYPE): Promise => { + initPresences: async (structureId: string, initType: INIT_TYPE): Promise => { return http.post(`/presences/initialization/structures/${structureId}`, {init_type: initType}); }, - initViesco: async (structureId: string, initType: INIT_TYPE, initForm: InitForm): Promise => { + initViesco: async (structureId: string, initType: INIT_TYPE, initForm: InitForm): Promise => { initForm.initType = initType; return http.post(`/viescolaire/structures/${structureId}/initialize`, initForm.toJSON()); }, getTeachersInitializationStatus: async (structureId: string): Promise => { return http.get(`/viescolaire/structures/${structureId}/initialization/teachers`) - .then((res: AxiosResponse) => res.data); + .then((res: HttpResponse) => res.data); }, getZones: (): IInitFormZone[] => { diff --git a/presences/src/main/resources/public/ts/sniplets/collective-absence-form.ts b/presences/src/main/resources/public/ts/sniplets/collective-absence-form.ts index cb8b2ec42..fdac9efa9 100644 --- a/presences/src/main/resources/public/ts/sniplets/collective-absence-form.ts +++ b/presences/src/main/resources/public/ts/sniplets/collective-absence-form.ts @@ -15,7 +15,7 @@ import { COLLECTIVE_ABSENCE_FORM_EVENTS, SNIPLET_FORM_EMIT_COLLECTIVE_ABSENCES_EVENTS } from '../core/enum/collective-absences-events'; -import {AxiosError, AxiosResponse} from 'axios'; +import { HttpError, HttpResponse } from 'entcore-toolkit'; import {PeriodFormUtils} from "@common/utils/periodForm"; import {REASON_TYPE_ID} from "@common/core/enum/reason-type-id"; @@ -220,7 +220,7 @@ const vm: IViewModel = { return; } collectiveAbsenceService.createCollectiveAbsence(window.structure.id, vm.prepareCollectiveForm()) - .then((res: AxiosResponse) => { + .then((res: HttpResponse) => { if (res.status === 200 || res.status === 201) { collectiveAbsenceForm.that.$emit(SNIPLET_FORM_EMIT_COLLECTIVE_ABSENCES_EVENTS.CREATION); vm.closeCollectiveLightBox(); @@ -228,7 +228,7 @@ const vm: IViewModel = { } else { toasts.warning('presences.collective.absences.form.create.error'); } - }).catch((_: AxiosError) => toasts.warning('presences.collective.absences.form.create.error')); + }).catch((_: HttpError) => toasts.warning('presences.collective.absences.form.create.error')); } }, @@ -239,7 +239,7 @@ const vm: IViewModel = { return; } collectiveAbsenceService.updateCollectiveAbsence(window.structure.id, vm.prepareCollectiveForm()) - .then((res: AxiosResponse) => { + .then((res: HttpResponse) => { if (res.status === 200 || res.status === 201) { collectiveAbsenceForm.that.$emit(SNIPLET_FORM_EMIT_COLLECTIVE_ABSENCES_EVENTS.EDIT); vm.closeCollectiveLightBox(); @@ -247,7 +247,7 @@ const vm: IViewModel = { } else { toasts.warning('presences.collective.absences.form.edit.error'); } - }).catch((_: AxiosError) => toasts.warning('presences.collective.absences.form.edit.error')); + }).catch((_: HttpError) => toasts.warning('presences.collective.absences.form.edit.error')); } }, @@ -317,7 +317,7 @@ const vm: IViewModel = { deleteCollectiveAbsence: async (): Promise => { if (vm.form && vm.form.id) { collectiveAbsenceService.deleteCollectiveAbsence(window.structure.id, vm.form.id) - .then((res: AxiosResponse) => { + .then((res: HttpResponse) => { if (res.status === 200 || res.status === 201) { collectiveAbsenceForm.that.$emit(SNIPLET_FORM_EMIT_COLLECTIVE_ABSENCES_EVENTS.DELETE); vm.closeCollectiveLightBox(); @@ -325,7 +325,7 @@ const vm: IViewModel = { } else { toasts.warning('presences.collective.absences.form.delete.error'); } - }).catch((_: AxiosError) => toasts.warning('presences.collective.absences.form.delete.error')); + }).catch((_: HttpError) => toasts.warning('presences.collective.absences.form.delete.error')); } }, @@ -452,7 +452,7 @@ const vm: IViewModel = { studentIds.push(student.id); }); collectiveAbsenceService.removeAbsenceFromCollectiveAbsence(window.structure.id, - vm.form.id, studentIds).then((res: AxiosResponse) => { + vm.form.id, studentIds).then((res: HttpResponse) => { if (res.status === 200) { vm.form.audiences.splice(index, 1); vm.updateData(); @@ -461,7 +461,7 @@ const vm: IViewModel = { } else { toasts.warning('presences.collective.absences.form.delete.absence.error'); } - }).catch((_: AxiosError) => toasts.warning('presences.collective.absences.form.delete.absence.error')); + }).catch((_: HttpError) => toasts.warning('presences.collective.absences.form.delete.absence.error')); } else { vm.form.audiences.splice(index, 1); } @@ -473,7 +473,7 @@ const vm: IViewModel = { removeStudent: (audienceId: string, studentId: string): void => { if (vm.form.id && vm.hasBeenAdded(studentId)) { collectiveAbsenceService.removeAbsenceFromCollectiveAbsence(window.structure.id, - vm.form.id, [studentId]).then((res: AxiosResponse) => { + vm.form.id, [studentId]).then((res: HttpResponse) => { if (res.status === 200) { vm.updateData(); toasts.confirm('presences.collective.absences.form.delete.absence.success'); @@ -481,7 +481,7 @@ const vm: IViewModel = { } else { toasts.warning('presences.collective.absences.form.delete.absence.error'); } - }).catch((_: AxiosError) => toasts.warning('presences.collective.absences.form.delete.absence.error')); + }).catch((_: HttpError) => toasts.warning('presences.collective.absences.form.delete.absence.error')); } vm.form.audiences.forEach((audience: ICollectiveAbsenceAudience) => { diff --git a/presences/src/main/resources/public/ts/sniplets/events-form.ts b/presences/src/main/resources/public/ts/sniplets/events-form.ts index 200d6abec..53498db95 100644 --- a/presences/src/main/resources/public/ts/sniplets/events-form.ts +++ b/presences/src/main/resources/public/ts/sniplets/events-form.ts @@ -17,7 +17,7 @@ import {IAngularEvent} from 'angular'; import {DateUtils} from '@common/utils'; import {ABSENCE_FORM_EVENTS, LATENESS_FORM_EVENTS} from '@common/core/enum/presences-event'; import {EventsUtils} from '../utilities'; -import {AxiosError, AxiosResponse} from 'axios'; +import { HttpError, HttpResponse } from 'entcore-toolkit'; import {PeriodFormUtils} from "@common/utils/periodForm"; import {REASON_TYPE_ID} from "@common/core/enum/reason-type-id"; import {EVENT_TYPE} from "@common/core/enum/event-type"; @@ -299,7 +299,7 @@ const vm: ViewModel = { vm.form = {} as IFormData; vm.event = new Absence(null, null, null, null); vm.switchEventTypeForm(eventType); - let response: AxiosResponse = await (vm.event).getAbsence(obj.absenceId); + let response: HttpResponse = await (vm.event).getAbsence(obj.absenceId); if (response.status === 200 || response.status === 201) { /* Assign response data to form edited */ vm.form.absences = [response.data]; @@ -434,9 +434,9 @@ const vm: ViewModel = { vm.deleteEvent(formEventType, false) .then(() => vm.createAbsence()) .then(() => vm.closeEventLightbox()) - .catch((err: AxiosError) => console.error(err)); + .catch((err: HttpError) => console.error(err)); } else { - vm.updateAbsence().catch((err: AxiosError) => console.error(err)); + vm.updateAbsence().catch((err: HttpError) => console.error(err)); } break; case EVENT_TYPE.LATENESS: @@ -447,9 +447,9 @@ const vm: ViewModel = { vm.deleteEvent(formEventType, false) .then(() => vm.createLateness()) .then(() => vm.closeEventLightbox()) - .catch((err: AxiosError) => console.error(err)); + .catch((err: HttpError) => console.error(err)); } else { - vm.updateLateness().catch((err: AxiosError) => console.error(err)); + vm.updateLateness().catch((err: HttpError) => console.error(err)); } break; } @@ -510,7 +510,7 @@ const vm: ViewModel = { toasts.warning(lang.translate('presences.invalid.form')); return; } - let response: AxiosResponse = await (vm.event).createAbsence(window.structure.id, vm.eventBody.reason_id, model.me.userId); + let response: HttpResponse = await (vm.event).createAbsence(window.structure.id, vm.eventBody.reason_id, model.me.userId); if (response.status === 200 || response.status === 201) { let presences: Presence[] = await presenceService.get({ structureId: window.structure.id, @@ -546,7 +546,7 @@ const vm: ViewModel = { toasts.warning(lang.translate('presences.invalid.form')); return; } - let responses: AxiosResponse[] = []; + let responses: HttpResponse[] = []; // In this const, we consider vm.form.absences without field "type" can be an event (on calendar view logical) // but sometimes we might have type field equal to events (seen on event list) so we double check const isEventTypeToInteract: boolean = !vm.form.absences.find((absence: IAbsence) => 'type' in absence) || @@ -565,7 +565,7 @@ const vm: ViewModel = { // we check if dataResponse contain 'events' field that represents the `createAbsence`'s API response // else we use the dataResponse itself as it is the `updateAbsence`'s API response const dataResponse: any = responses - .find((response: AxiosResponse) => response.status === 200 || response.status === 201).data; + .find((response: HttpResponse) => response.status === 200 || response.status === 201).data; let dataAbsenceEventResponse: AbsenceEventResponse; // we remain undefined if dataResponse has not found any response @@ -624,7 +624,7 @@ const vm: ViewModel = { }, async deleteAbsence(canReload: boolean): Promise { - let responses: Array = []; + let responses: Array = []; for (const absence of vm.form.absences) { if ('type' in absence && absence.type === EventsUtils.ALL_EVENTS.absence) { responses.push(await (vm.event).deleteAbsence(absence.id)); @@ -633,7 +633,7 @@ const vm: ViewModel = { } } - let failedResponse: AxiosResponse = responses.find((response: AxiosResponse) => response.status != 200 && response.status != 201); + let failedResponse: HttpResponse = responses.find((response: HttpResponse) => response.status != 200 && response.status != 201); if (failedResponse) { toasts.warning(failedResponse.data.toString()); } else { @@ -664,7 +664,7 @@ const vm: ViewModel = { return; } eventService.createLatenessEvent(vm.eventBody, window.structure.id) - .then((response: AxiosResponse) => { + .then((response: HttpResponse) => { if (response.status === 200 || response.status === 201) { vm.closeEventLightbox(); toasts.confirm(lang.translate('presences.lateness.form.create.succeed')); @@ -674,7 +674,7 @@ const vm: ViewModel = { toasts.warning(lang.translate('presences.lateness.form.create.no.register')); } }) - .catch((_: AxiosError) => { + .catch((_: HttpError) => { toasts.warning(lang.translate('presences.lateness.form.create.no.register')); }); }, @@ -686,7 +686,7 @@ const vm: ViewModel = { return; } eventService.updateEvent(vm.form.id, vm.eventBody) - .then((response: AxiosResponse) => { + .then((response: HttpResponse) => { if (response.status === 200 || response.status === 201) { vm.closeEventLightbox(); toasts.confirm(lang.translate('presences.lateness.form.edit.succeed')); @@ -696,14 +696,14 @@ const vm: ViewModel = { toasts.warning(lang.translate('presences.lateness.form.edit.error')); } }) - .catch((_: AxiosError) => { + .catch((_: HttpError) => { toasts.warning(lang.translate('presences.lateness.form.edit.error')); }); }, async deleteLateness(canReload: boolean): Promise { eventService.deleteEvent(vm.form.id) - .then((response: AxiosResponse) => { + .then((response: HttpResponse) => { if (response.status === 200 || response.status === 201) { toasts.confirm(lang.translate('presences.lateness.form.delete.succeed')); if (canReload) { @@ -714,7 +714,7 @@ const vm: ViewModel = { toasts.warning(lang.translate('presences.lateness.form.delete.error')); } }) - .catch((_: AxiosError) => { + .catch((_: HttpError) => { toasts.warning(lang.translate('presences.lateness.form.delete.error')); }); }, diff --git a/presences/src/main/resources/public/ts/sniplets/exemption-form.ts b/presences/src/main/resources/public/ts/sniplets/exemption-form.ts index 6cfdefea3..491afd740 100644 --- a/presences/src/main/resources/public/ts/sniplets/exemption-form.ts +++ b/presences/src/main/resources/public/ts/sniplets/exemption-form.ts @@ -5,7 +5,7 @@ import {SNIPLET_FORM_EMIT_EVENTS, SNIPLET_FORM_EVENTS} from '@common/model' import {DateUtils, StudentsSearch} from "@common/utils"; import {SearchService, searchService, ViescolaireService} from "@common/services"; import {IAngularEvent} from "angular"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; console.log("ExemptionForm sniplet"); @@ -232,7 +232,7 @@ const vm: ViewModel = { vm.form.endDateRecursive = vm.form.endDate; } try { - let response: AxiosResponse = await vm.form.save(); + let response: HttpResponse = await vm.form.save(); if (vm.form.id) { vm.updateAfterSaveOrDelete(response, lang.translate('presences.exemptions.form.edit.succeed')); } else { diff --git a/presences/src/main/resources/public/ts/sniplets/forgotten-notebook-form.ts b/presences/src/main/resources/public/ts/sniplets/forgotten-notebook-form.ts index a2c207575..16bdfc565 100644 --- a/presences/src/main/resources/public/ts/sniplets/forgotten-notebook-form.ts +++ b/presences/src/main/resources/public/ts/sniplets/forgotten-notebook-form.ts @@ -3,7 +3,7 @@ import {alertService, forgottenNotebookService, NotebookRequest} from "../servic import {idiom as lang, moment, toasts} from "entcore"; import {DateUtils} from "@common/utils"; import {AlertType} from "../models"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; console.log("forgottenNotebookFormSniplets"); @@ -131,7 +131,7 @@ const vm: ViewModel = { resetForbiddenNotebookCount: async (studentId: string): Promise => { try { - let response: AxiosResponse = await alertService.resetStudentAlertsCount(window.structure.id, studentId, + let response: HttpResponse = await alertService.resetStudentAlertsCount(window.structure.id, studentId, AlertType[AlertType.FORGOTTEN_NOTEBOOK]); if (response.status === 200 || response.status === 201) { diff --git a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-action-manage.ts b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-action-manage.ts index adb630797..8808b0658 100644 --- a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-action-manage.ts +++ b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-action-manage.ts @@ -1,7 +1,7 @@ import {actionService} from "../../services"; import {Action, ActionRequest} from "../../models"; import {PRESENCES_ACTION} from "@common/core/enum/presences-event"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {toasts} from "entcore"; declare const window: any; @@ -22,7 +22,7 @@ interface ViewModel { deleteAction(action: Action): void; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; openActionLightbox(action: Action): void; @@ -78,7 +78,7 @@ const vm: ViewModel = { } }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.getAction(); } diff --git a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-discipline-manage.ts b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-discipline-manage.ts index a6cfaed95..097d605e9 100644 --- a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-discipline-manage.ts +++ b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-discipline-manage.ts @@ -1,4 +1,4 @@ -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {Discipline, DisciplineRequest} from "../../models"; import {disciplineService} from "../../services"; import {PRESENCES_DISCIPLINE} from "@common/core/enum/presences-event"; @@ -16,7 +16,7 @@ interface ViewModel { hasDisciplines(): boolean; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; getDisciplines(): Promise; @@ -82,7 +82,7 @@ const vm: ViewModel = { await disciplineService.update(form); }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.getDisciplines(); } diff --git a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-absence.ts b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-absence.ts index 9af9983a6..9530860db 100644 --- a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-absence.ts +++ b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-absence.ts @@ -1,5 +1,5 @@ import {ReasonService, reasonService} from "../../../services/ReasonService"; -import {AxiosError, AxiosResponse} from "axios"; +import { HttpError, HttpResponse } from 'entcore-toolkit'; import {Reason, ReasonRequest} from "../../../models/Reason"; import {idiom, toasts} from "entcore"; import {ReasonSnipletModel} from "./presences-reason-manager"; @@ -80,7 +80,7 @@ export class AbsenceReasonSniplet implements ReasonSnipletModel { } this.form.structureId = window.model.vieScolaire.structure.id; try { - let response: AxiosResponse = await this.reasonService.create(this.form, this.reasonTypeId); + let response: HttpResponse = await this.reasonService.create(this.form, this.reasonTypeId); this.proceedAfterAction(response); } catch (err) { console.error(err); @@ -94,7 +94,7 @@ export class AbsenceReasonSniplet implements ReasonSnipletModel { async deleteReason(reason: Reason): Promise { try { - let response: AxiosResponse = await this.reasonService.delete(reason.id); + let response: HttpResponse = await this.reasonService.delete(reason.id); this.proceedAfterAction(response); } catch (err) { console.error(err) @@ -116,7 +116,7 @@ export class AbsenceReasonSniplet implements ReasonSnipletModel { async updateReason(): Promise { try { - let response: AxiosResponse = await this.reasonService.update(this.formEdit); + let response: HttpResponse = await this.reasonService.update(this.formEdit); this.proceedAfterAction(response); this.closeReasonLightbox(); } catch (err) { @@ -136,16 +136,16 @@ export class AbsenceReasonSniplet implements ReasonSnipletModel { form.excludeAlertRegularised = (reason.reason_alert_rules).includes(ALERT_RULE.REGULARIZED); form.excludeAlertNoRegularised = (reason.reason_alert_rules).includes(ALERT_RULE.UNREGULARIZED); form.structureId = reason.structure_id; - await this.reasonService.update(form).catch((err: AxiosError) => { + await this.reasonService.update(form).catch((err: HttpError) => { toasts.warning('presences.reason.error'); console.error(err) }); } - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { - this.getReasons().catch((e: AxiosError) => console.error(e)); + this.getReasons().catch((e: HttpError) => console.error(e)); } } diff --git a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-lateness.ts b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-lateness.ts index eb0d85307..cf1e11a8d 100644 --- a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-lateness.ts +++ b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manage-lateness.ts @@ -1,7 +1,7 @@ import {idiom, toasts} from "entcore"; import {Reason, ReasonRequest} from "../../../models/Reason"; import {ReasonService, reasonService} from "../../../services/ReasonService"; -import {AxiosError, AxiosResponse} from "axios"; +import { HttpError, HttpResponse } from 'entcore-toolkit'; import {ReasonSnipletModel} from "./presences-reason-manager"; import {safeApply} from "@common/utils"; import {REASON_TYPE_ID} from "@common/core/enum/reason-type-id"; @@ -80,7 +80,7 @@ export class LatenessReasonSniplet implements ReasonSnipletModel { } this.form.structureId = window.model.vieScolaire.structure.id; try { - let response: AxiosResponse = await this.reasonService.create(this.form, this.reasonTypeId); + let response: HttpResponse = await this.reasonService.create(this.form, this.reasonTypeId); this.proceedAfterAction(response); } catch (err) { console.error(err); @@ -94,7 +94,7 @@ export class LatenessReasonSniplet implements ReasonSnipletModel { async deleteReason(reason: Reason): Promise { try { - let response: AxiosResponse = await this.reasonService.delete(reason.id); + let response: HttpResponse = await this.reasonService.delete(reason.id); this.proceedAfterAction(response); } catch (err) { console.error(err) @@ -116,7 +116,7 @@ export class LatenessReasonSniplet implements ReasonSnipletModel { async updateReason(): Promise { try { - let response: AxiosResponse = await this.reasonService.update(this.formEdit); + let response: HttpResponse = await this.reasonService.update(this.formEdit); this.proceedAfterAction(response); this.closeReasonLightbox(); } catch (err) { @@ -136,15 +136,15 @@ export class LatenessReasonSniplet implements ReasonSnipletModel { form.excludeAlertRegularised = (reason.reason_alert_rules).includes(ALERT_RULE.REGULARIZED); form.excludeAlertNoRegularised = (reason.reason_alert_rules).includes(ALERT_RULE.UNREGULARIZED); form.structureId = reason.structure_id; - await this.reasonService.update(form).catch((err: AxiosError) => { + await this.reasonService.update(form).catch((err: HttpError) => { toasts.warning('presences.reason.error'); console.error(err) }); } - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { - this.getReasons().catch((e: AxiosError) => console.error(e)); + this.getReasons().catch((e: HttpError) => console.error(e)); } } diff --git a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manager.ts b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manager.ts index 5523b39cd..b7e7d723c 100644 --- a/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manager.ts +++ b/presences/src/main/resources/public/ts/sniplets/presences-manage/presences-reason/presences-reason-manager.ts @@ -1,6 +1,6 @@ import {idiom} from "entcore"; import {Reason, ReasonRequest} from "@presences/models"; -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; export interface ReasonSnipletModel { lang: typeof idiom; @@ -34,6 +34,6 @@ export interface ReasonSnipletModel { deleteReason(reason: Reason): void; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; } \ No newline at end of file diff --git a/presences/src/main/resources/public/ts/sniplets/presences-manage/presencesManageLightbox.ts b/presences/src/main/resources/public/ts/sniplets/presences-manage/presencesManageLightbox.ts index 0de8405eb..9ac8a851a 100644 --- a/presences/src/main/resources/public/ts/sniplets/presences-manage/presencesManageLightbox.ts +++ b/presences/src/main/resources/public/ts/sniplets/presences-manage/presencesManageLightbox.ts @@ -1,4 +1,4 @@ -import {AxiosResponse} from "axios"; +import { HttpResponse } from 'entcore-toolkit'; import {PRESENCES_ACTION, PRESENCES_DISCIPLINE} from "@common/core/enum/presences-event"; import {IAngularEvent} from "angular"; import {actionService, disciplineService} from "../../services"; @@ -22,7 +22,7 @@ interface ViewModel { updatePresencesManageLightbox(): Promise; - proceedAfterAction(response: AxiosResponse): void; + proceedAfterAction(response: HttpResponse): void; } const vm: ViewModel = { @@ -79,7 +79,7 @@ const vm: ViewModel = { }, - proceedAfterAction(response: AxiosResponse): void { + proceedAfterAction(response: HttpResponse): void { if (response.status === 200 || response.status === 201) { vm.editPresencesManageLightbox = false; } diff --git a/statistics-presences/src/main/resources/public/ts/controllers/main.ts b/statistics-presences/src/main/resources/public/ts/controllers/main.ts index eac514a2b..e85fc1025 100644 --- a/statistics-presences/src/main/resources/public/ts/controllers/main.ts +++ b/statistics-presences/src/main/resources/public/ts/controllers/main.ts @@ -24,7 +24,7 @@ import {EXPORT_TYPE} from "../core/enums/export-type.enum"; import {Weekly} from "@statistics/indicator/Weekly"; import {SLOT_HEIGHT} from "../../constants/calendar"; import {REASON_TYPE_ID} from "@common/core/enum/reason-type-id"; -import {AxiosError} from "axios"; +import { HttpError } from 'entcore-toolkit'; import {GroupingService} from "@common/services"; import {Grouping} from "@common/model/grouping"; @@ -468,7 +468,7 @@ export const mainController = ng.controller('MainController', .then(() => { toasts.info('statistics-presences.indicator.Global.student.refresh.success'); vm.loading = false; - }).catch((err: AxiosError) => { + }).catch((err: HttpError) => { toasts.warning('statistics-presences.indicator.Global.student.refresh.error'); console.error(err, err.message); vm.loading = false; diff --git a/statistics-presences/src/main/resources/public/ts/indicator/Global.ts b/statistics-presences/src/main/resources/public/ts/indicator/Global.ts index 1fff29708..7117cecfa 100644 --- a/statistics-presences/src/main/resources/public/ts/indicator/Global.ts +++ b/statistics-presences/src/main/resources/public/ts/indicator/Global.ts @@ -5,7 +5,7 @@ import {IPunishmentType} from '@incidents/models/PunishmentType'; import {Reason} from '@presences/models'; import {INDICATOR_TYPE} from "../core/constants/IndicatorType"; import {GlobalResponse, GlobalStatistics, IGlobal} from "../model/Global"; -import {AxiosError} from "axios"; +import { HttpError } from 'entcore-toolkit'; import {DISPLAY_TYPE} from "../core/constants/DisplayMode"; import {DateUtils} from "@common/utils"; import {model} from "entcore"; @@ -61,7 +61,7 @@ export class Global extends Indicator { }; resolve(); }) - .catch((error: AxiosError) => { + .catch((error: HttpError) => { reject(error); }); }); diff --git a/statistics-presences/src/main/resources/public/ts/indicator/Monthly.ts b/statistics-presences/src/main/resources/public/ts/indicator/Monthly.ts index 62e991aae..b38f2d39a 100644 --- a/statistics-presences/src/main/resources/public/ts/indicator/Monthly.ts +++ b/statistics-presences/src/main/resources/public/ts/indicator/Monthly.ts @@ -5,7 +5,7 @@ import {IPunishmentType} from '@incidents/models/PunishmentType'; import {ISchoolYearPeriod, Reason} from '@presences/models'; import {INDICATOR_TYPE} from "../core/constants/IndicatorType"; import {IMonthly, IMonthlyGraph, MonthlyStat, MonthlyStatistics, MonthlyStats, MonthlyStudent} from '../model/Monthly'; -import {AxiosError} from 'axios'; +import { HttpError } from 'entcore-toolkit'; import {DISPLAY_TYPE} from "../core/constants/DisplayMode"; import {DateUtils} from "@common/utils"; import {ViescolaireService} from "@common/services"; @@ -58,7 +58,7 @@ export class Monthly extends Indicator { this._mapResults(res); resolve(); }) - .catch((error: AxiosError) => { + .catch((error: HttpError) => { reject(error); }); }); @@ -72,7 +72,7 @@ export class Monthly extends Indicator { this.graphValues = res; resolve(); }) - .catch((error: AxiosError) => { + .catch((error: HttpError) => { reject(error); }); }); diff --git a/statistics-presences/src/main/resources/public/ts/indicator/Weekly.ts b/statistics-presences/src/main/resources/public/ts/indicator/Weekly.ts index 5424944f0..6e379ad6d 100644 --- a/statistics-presences/src/main/resources/public/ts/indicator/Weekly.ts +++ b/statistics-presences/src/main/resources/public/ts/indicator/Weekly.ts @@ -7,7 +7,7 @@ import {IWeekly, IWeeklyResponse, WeeklyStatistics, WeeklyStatisticsResponse} fr import {DateUtils} from "@common/utils"; import {DISPLAY_TYPE} from "../core/constants/DisplayMode"; import {IndicatorFactory} from '../indicator'; -import {AxiosError} from "axios"; +import { HttpError } from 'entcore-toolkit'; import {idiom, idiom as lang, model, moment, toasts} from "entcore"; import {ViescolaireService} from "@common/services"; import {timeslotClasseService} from "@common/services/TimeslotClasseService"; @@ -66,7 +66,7 @@ export class Weekly extends Indicator { this.values = {slots: this._mapResults(res)} resolve(); }) - .catch((error: AxiosError) => { + .catch((error: HttpError) => { reject(error); }); }); diff --git a/statistics-presences/src/main/resources/public/ts/services/__tests__/indicator.service.test.ts b/statistics-presences/src/main/resources/public/ts/services/__tests__/indicator.service.test.ts index c0543c35e..0b68acf0f 100644 --- a/statistics-presences/src/main/resources/public/ts/services/__tests__/indicator.service.test.ts +++ b/statistics-presences/src/main/resources/public/ts/services/__tests__/indicator.service.test.ts @@ -3,10 +3,15 @@ jest.mock('entcore', () => ({ ng: {service: jest.fn()} })) +jest.mock('entcore-toolkit', () => ({ + ...jest.requireActual('entcore-toolkit'), + http: {get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(), postFile: jest.fn(), putFile: jest.fn()} +})); + import {IndicatorBody} from "../../model/Indicator"; import {indicatorService} from "../indicator.service"; -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; +import {http} from 'entcore-toolkit'; +import {mockHttpResponse} from '@test-utils/httpMock'; describe('IndicatorService', () => { const body: IndicatorBody = { @@ -25,24 +30,26 @@ describe('IndicatorService', () => { const page: number = 1; it('should return data when API fetchIndicator request is correctly called', done => { - let mock = new MockAdapter(axios); const data = {response: true}; - mock.onPost(`/statistics-presences/structures/${structure}/indicators/${name}?page=${page}`, body).reply(200, data); + const url = `/statistics-presences/structures/${structure}/indicators/${name}?page=${page}`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'post'})); indicatorService.fetchIndicator(structure, name, page, body).then(response => { + expect(http.post).toHaveBeenCalledWith(url, body); expect(response).toEqual(data); done(); }); }); it('should return data when API fetchGraphIndicator request is correctly called', done => { - let mock = new MockAdapter(axios); const data = {response: true}; - mock.onPost(`/statistics-presences/structures/${structure}/indicators/${name}/graph`, body).reply(200, data); + const url = `/statistics-presences/structures/${structure}/indicators/${name}/graph`; + (http.post as jest.Mock).mockResolvedValueOnce(mockHttpResponse(data, {url, method: 'post'})); indicatorService.fetchGraphIndicator(structure, name, body).then(response => { + expect(http.post).toHaveBeenCalledWith(url, body); expect(response).toEqual(data); done(); }); }); }) -; \ No newline at end of file +; diff --git a/statistics-presences/src/main/resources/public/ts/services/indicator.service.ts b/statistics-presences/src/main/resources/public/ts/services/indicator.service.ts index e67eb4d2b..5faceb2c2 100644 --- a/statistics-presences/src/main/resources/public/ts/services/indicator.service.ts +++ b/statistics-presences/src/main/resources/public/ts/services/indicator.service.ts @@ -1,7 +1,7 @@ import {ng, moment} from 'entcore' import {GlobalResponse} from "@statistics/model/Global"; import {IMonthly, IMonthlyGraph} from "@statistics/model/Monthly"; -import http, {AxiosResponse} from "axios"; +import { http, HttpResponse } from 'entcore-toolkit'; import {IndicatorBody} from "../model/Indicator"; import {IWeekly, IWeeklyResponse, WeeklyStatistics} from "@statistics/model/Weekly"; @@ -10,21 +10,21 @@ export interface IndicatorService { fetchGraphIndicator(structureId: string, indicatorName: string, body: IndicatorBody): Promise; - refreshStudentsStats(structureId: string, arrayStudentIds: Array): Promise; + refreshStudentsStats(structureId: string, arrayStudentIds: Array): Promise; } export const indicatorService: IndicatorService = { fetchIndicator: async (structure: string, name: string, page: number, body: IndicatorBody): Promise => { return http.post(`/statistics-presences/structures/${structure}/indicators/${name}?page=${page}`, body) - .then((res: AxiosResponse) => res.data); + .then((res: HttpResponse) => res.data); }, fetchGraphIndicator: async (structureId: string, indicatorName: string, body: IndicatorBody): Promise => { return http.post(`/statistics-presences/structures/${structureId}/indicators/${indicatorName}/graph`, body) - .then((res: AxiosResponse) => res.data); + .then((res: HttpResponse) => res.data); }, - refreshStudentsStats(structureId: string, arrayStudentIds: Array): Promise { + refreshStudentsStats(structureId: string, arrayStudentIds: Array): Promise { return http.post(`/statistics-presences/structures/${structureId}/process/students/statistics/tasks`, {studentIds: arrayStudentIds}) } diff --git a/test-utils/httpMock.ts b/test-utils/httpMock.ts new file mode 100644 index 000000000..dd053a6cf --- /dev/null +++ b/test-utils/httpMock.ts @@ -0,0 +1,29 @@ +export interface MockHttpResponseOptions { + status?: number; + url?: string; + method?: string; + data?: any; +} + +/** + * Builds a fake HttpResponse (entcore-toolkit's `http` bridge shape), for use with + * `(http.get as jest.Mock).mockResolvedValueOnce(mockHttpResponse(...))` once `entcore-toolkit` + * is jest-mocked. Replaces the pre-migration axios-mock-adapter pattern: mocking the app's own + * `axios` import never intercepted requests made through the bridge (entcore-toolkit bundles its + * own internal axios instance, a separate object graph), so URL/method mocking must happen at the + * `http` module boundary instead. + */ +export function mockHttpResponse(data: T, opts: MockHttpResponseOptions = {}): any { + const {status = 200, url = '', method = 'get', data: requestData} = opts; + return { + data, + status, + statusText: 'OK', + headers: {}, + config: { + url, + method, + data: requestData, + }, + }; +} diff --git a/tsconfig.json b/tsconfig.json index c7ea60566..5c0aaa023 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -33,6 +33,9 @@ ], "@statistics/*": [ "statistics-presences/src/main/resources/public/ts/*" + ], + "@test-utils/*": [ + "test-utils/*" ] } },