feat: add contact service

This commit is contained in:
2025-12-14 20:40:50 -03:00
parent 87d7557cf3
commit f74d15713c
2 changed files with 110 additions and 0 deletions

View File

@@ -0,0 +1,75 @@
import { TestBed } from '@angular/core/testing';
import { Response } from '../../models/Response';
import { ContactService } from './contact.service';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { environment } from '../../../environments/environment';
import { ContactDTO } from '../../models/ContactDTO';
describe('ContactService', () => {
let service: ContactService;
let httpTestingController: HttpTestingController;
let RES_MOCK: Response<any>;
let endpointURL = environment.apiUrl + '/contacts';
beforeEach(() => {
TestBed.configureTestingModule({
imports: [],
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(ContactService);
httpTestingController = TestBed.inject(HttpTestingController);
RES_MOCK = {
data: null,
errors: [],
message: '',
success: true,
};
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should GET contacts from the contacts ep', () => {
const CONTACTS_MOCK = [new ContactDTO(1, 'mock1'), new ContactDTO(2, 'mock2')];
service.getAll().subscribe();
const req = httpTestingController.expectOne(endpointURL);
expect(req.request.method).toEqual('GET');
RES_MOCK.data = CONTACTS_MOCK;
req.flush(RES_MOCK);
httpTestingController.verify();
});
it('should POST contact to the contacts ep', () => {
const CONTACT_MOCK = new ContactDTO(undefined, 'mock');
service.save(CONTACT_MOCK).subscribe();
const postReq = httpTestingController.expectOne(endpointURL);
expect(postReq.request.method).toEqual('POST');
expect(postReq.request.body).toEqual(CONTACT_MOCK);
CONTACT_MOCK.id = 1;
RES_MOCK.data = CONTACT_MOCK
postReq.flush(RES_MOCK);
const getReq = httpTestingController.expectOne(endpointURL);
expect(getReq.request.method).toEqual('GET');
RES_MOCK.data = [CONTACT_MOCK];
getReq.flush(RES_MOCK);
httpTestingController.verify();
});
it('should DELETE with the given ID to the contacts ep', () => {
const ID_MOCK = 1;
service.delete(ID_MOCK).subscribe();
const deleteReq = httpTestingController.expectOne(`${endpointURL}/${ID_MOCK}`);
expect(deleteReq.request.method).toEqual('DELETE');
RES_MOCK.message = "Contact deleted successfully";
deleteReq.flush(RES_MOCK);
const getReq = httpTestingController.expectOne(endpointURL);
expect(getReq.request.method).toEqual('GET');
RES_MOCK.data = [];
RES_MOCK.message = '';
getReq.flush(RES_MOCK);
});
});