UNPKG

@universis/common

Version:

Universis - common directives and services

94 lines (82 loc) 3.29 kB
#### ApiTestingModule An angular module for testing api calls and services. ### Usage Import ApiTestingModule in any test spec: import {ApiTestingModule} from '@universis/common'; Add ApiTestingModule.forRoot() in testing module configuration: describe('TestService', () => { let mockApi: ApiTestingController; beforeEach(async(() => { // noinspection JSIgnoredPromiseFromCall TestBed.configureTestingModule({ imports: [ CommonModule, MostModule.forRoot({ base: '/api/', options: { useMediaTypeExtensions: false } }), ApiTestingModule.forRoot() ], providers: [ AuthenticationService, { provide: ConfigurationService, useClass: TestingConfigurationService } ], declarations: [ ], }).compileComponents(); // get api test controller mockApi = TestBed.get(ApiTestingController); })); } and finally use ApiTestingController to handle api requests and responses. it('should use authentication callback', inject([AuthenticationService], async (authService: AuthenticationService) => { // add match url mockApi.match({ url: '/api/users/me/', method: 'GET' }).map(request => { // register request mapper and return data request.flush({ id: 1, name: 'user@example.com', description: 'Test User', groups: [ { name: 'Administrators' } ] }); }); // call authentication service callback const result = await authService.callback('a-testing-token--'); expect(result).toBeTruthy(); expect(result.name).toBe('user@example.com'); })); or test error handling it('should throw token expired error', inject([AuthenticationService], async (authService: AuthenticationService) => { // add match url mockApi.match({ url: '/api/users/me/', method: 'GET' }).map((request: TestRequest) => { // register request mapper and return data request.error(new ErrorEvent('Token Not Found'), { status: 404, statusText: 'Token Not Found' }); }); // call authentication service callback authService.callback('a-testing-token--').then( result => { expect(false).toBe(true, 'Expected an error to be thrown.'); }).catch( err => { expect(err).toBeTruthy(); expect(err.status).toBe(404); }); }));