Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions src/app/error.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { HttpErrorHandler } from './error.service';

describe('HttpErrorHandler', () => {
let handler: HttpErrorHandler;

beforeEach(() => {
handler = new HttpErrorHandler();
spyOn(console, 'error');
});

describe('createHandleError', () => {
it('should return a curried function bound to the service name', () => {
const handleError = handler.createHandleError('TestService');
expect(typeof handleError).toBe('function');
});
});

describe('handleError', () => {
it('should handle a client-side ErrorEvent', (done) => {
const errorEvent = new ErrorEvent('Network error', {
message: 'simulated network error',
});
const errorResponse = new HttpErrorResponse({
error: errorEvent,
status: 0,
statusText: 'Unknown Error',
});

const errorFn = handler.handleError('TestService', 'testOp', []);
errorFn(errorResponse).subscribe({
error: (msg) => {
expect(msg).toBe('simulated network error');
expect(console.error).toHaveBeenCalledWith(errorResponse);
expect(console.error).toHaveBeenCalledWith(
'TestService::testOp failed: simulated network error'
);
done();
},
});
});

it('should handle a server-side error with status code', (done) => {
const errorResponse = new HttpErrorResponse({
error: 'Not Found',
status: 404,
statusText: 'Not Found',
});

const errorFn = handler.handleError('TestService', 'testOp', []);
errorFn(errorResponse).subscribe({
error: (msg) => {
expect(msg).toBe('server returned code 404 with body "Not Found"');
expect(console.error).toHaveBeenCalledWith(errorResponse);
done();
},
});
});

it('should extract Spring MVC errorMessage from errors header', (done) => {
const headers = new HttpHeaders().set(
'errors',
JSON.stringify([{ errorMessage: 'lastName must not be empty' }])
);
const errorResponse = new HttpErrorResponse({
error: 'Bad Request',
status: 400,
statusText: 'Bad Request',
headers,
});

const errorFn = handler.handleError('TestService', 'testOp', []);
errorFn(errorResponse).subscribe({
error: (msg) => {
expect(msg).toBe('lastName must not be empty');
done();
},
});
});

it('should fall back to default message when errors header has no errorMessage', (done) => {
const headers = new HttpHeaders().set(
'errors',
JSON.stringify([{ field: 'lastName' }])
);
const errorResponse = new HttpErrorResponse({
error: 'Bad Request',
status: 400,
statusText: 'Bad Request',
headers,
});

const errorFn = handler.handleError('TestService', 'testOp', []);
errorFn(errorResponse).subscribe({
error: (msg) => {
expect(msg).toBe('server returned code 400 with body "Bad Request"');
done();
},
});
});

it('should fall back to default message when errors header is an empty array', (done) => {
const headers = new HttpHeaders().set('errors', JSON.stringify([]));
const errorResponse = new HttpErrorResponse({
error: 'Bad Request',
status: 400,
statusText: 'Bad Request',
headers,
});

const errorFn = handler.handleError('TestService', 'testOp', []);
errorFn(errorResponse).subscribe({
error: (msg) => {
expect(msg).toBe('server returned code 400 with body "Bad Request"');
done();
},
});
});

it('should use default parameter values when none are provided', (done) => {
const errorResponse = new HttpErrorResponse({
error: 'Server Error',
status: 500,
statusText: 'Internal Server Error',
});

const errorFn = handler.handleError();
errorFn(errorResponse).subscribe({
error: (msg) => {
expect(console.error).toHaveBeenCalledWith(
'::operation failed: server returned code 500 with body "Server Error"'
);
done();
},
});
});
});
});
38 changes: 13 additions & 25 deletions src/app/owners/owner.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import { HttpErrorHandler } from '../error.service';
import { OwnerService } from './owner.service';
import { Owner } from './owner';
import { Type } from '@angular/core';
import { defer } from 'rxjs';

describe('OwnerService', () => {
let httpTestingController: HttpTestingController;
Expand Down Expand Up @@ -171,29 +170,18 @@ describe('OwnerService', () => {
expect(req.request.body).toEqual(null);
});

it('search for delete Owner', () => {

const errorResponse = new HttpErrorResponse({
error: '404 error',
status: 404,
statusText: 'Not Found'
});

httpClientSpy.get.and.returnValue(asyncError(errorResponse));

ownerService.getOwnerById(1).subscribe((owners) => {
fail('Should have failed with 404 error'),
(error: HttpErrorResponse) => {
expect(error.status).toEqual(404);
expect(error.error).toContain('404 error');
}});

const req = httpTestingController.expectOne(
{ method: 'GET', url:ownerService.entityUrl + '/1' });
it('should handle error when getting owner by id', () => {
ownerService.getOwnerById(1).subscribe(
() => fail('expected an error, not owner'),
(errorMsg) => {
expect(errorMsg).toContain('404');
}
);

});
const req = httpTestingController.expectOne(
ownerService.entityUrl + '/1'
);
expect(req.request.method).toEqual('GET');
req.flush('404 error', { status: 404, statusText: 'Not Found' });
});
});

export function asyncError<T>(errorObject: any) {
return defer(() => Promise.reject(errorObject));
}
148 changes: 114 additions & 34 deletions src/app/pets/pet.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,123 @@
/*
*
* * Copyright 2016-2017 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/

/* tslint:disable:no-unused-variable */


/**
* @author Vitaliy Fedoriv
*/

import { inject, TestBed, waitForAsync } from '@angular/core/testing';
import {PetService} from './pet.service';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
import {HttpClient} from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import {
HttpClientTestingModule,
HttpTestingController,
} from '@angular/common/http/testing';
import { HttpResponse } from '@angular/common/http';
import { Type } from '@angular/core';

import { PetService } from './pet.service';
import { Pet } from './pet';
import { HttpErrorHandler } from '../error.service';
import { environment } from '../../environments/environment';

describe('PetService', () => {
let httpTestingController: HttpTestingController;
let petService: PetService;
const entityUrl = environment.REST_API_URL + 'pets';

const testPet: Pet = {
id: 1,
name: 'Leo',
birthDate: '2010-09-07',
type: { id: 1, name: 'cat' },
ownerId: 1,
owner: {
id: 1,
firstName: 'George',
lastName: 'Franklin',
address: '110 W. Liberty St.',
city: 'Madison',
telephone: '6085551023',
pets: [],
},
visits: [],
};

beforeEach(() => {
TestBed.configureTestingModule({
// Import the HttpClient mocking services
imports: [HttpClientTestingModule],
providers: [PetService]
providers: [PetService, HttpErrorHandler],
});
httpTestingController = TestBed.inject<HttpTestingController>(
HttpTestingController as Type<HttpTestingController>
);
petService = TestBed.inject(PetService);
});

afterEach(() => {
httpTestingController.verify();
});

it('should return expected pets (getPets)', () => {
const expectedPets: Pet[] = [testPet];

petService.getPets().subscribe(
(pets) => expect(pets).toEqual(expectedPets),
fail
);

const req = httpTestingController.expectOne(entityUrl);
expect(req.request.method).toEqual('GET');
req.flush(expectedPets);
});

it('should return a pet by id (getPetById)', () => {
petService.getPetById(1).subscribe(
(pet) => expect(pet).toEqual(testPet),
fail
);

const req = httpTestingController.expectOne(entityUrl + '/1');
expect(req.request.method).toEqual('GET');
req.flush(testPet);
});

it('should add a pet under the correct owner URL (addPet)', () => {
const newPet: Pet = { ...testPet, id: null };
const ownersUrl = environment.REST_API_URL + 'owners/1/pets';

petService.addPet(newPet).subscribe(
(pet) => expect(pet).toEqual(newPet),
fail
);

const req = httpTestingController.expectOne(ownersUrl);
expect(req.request.method).toEqual('POST');
expect(req.request.body).toEqual(newPet);
const expectedResponse = new HttpResponse({
status: 201,
statusText: 'Created',
body: newPet,
});
req.event(expectedResponse);
});

it('should update a pet (updatePet)', () => {
const updatedPet: Pet = { ...testPet, name: 'Leopold' };

petService.updatePet('1', updatedPet).subscribe(
(pet) => expect(pet).toEqual(updatedPet),
fail
);

const req = httpTestingController.expectOne(entityUrl + '/1');
expect(req.request.method).toEqual('PUT');
expect(req.request.body).toEqual(updatedPet);
const expectedResponse = new HttpResponse({
status: 204,
statusText: 'No Content',
body: updatedPet,
});
req.event(expectedResponse);
});

it('should ...', waitForAsync(inject([HttpTestingController], (petService: PetService, http: HttpClient) => {
expect(petService).toBeTruthy();
})));
it('should delete a pet (deletePet)', () => {
petService.deletePet('1').subscribe();

const req = httpTestingController.expectOne(entityUrl + '/1');
expect(req.request.method).toEqual('DELETE');
expect(req.request.body).toEqual(null);
req.flush(null);
});
});
Loading