Skip to content

Instantly share code, notes, and snippets.

@btroncone
Last active September 4, 2019 08:16
Show Gist options
  • Save btroncone/b1ef4df357278d0af33372302eb2141e to your computer and use it in GitHub Desktop.
Save btroncone/b1ef4df357278d0af33372302eb2141e to your computer and use it in GitHub Desktop.
Angular service testing (constructor)
import { inject, TestBed } from '@angular/core/testing';
import { of } from 'rxjs/observable/of';
import { LoggingService, LocalStorageService } from '../';
import { RouterEventService } from '../../routing';
export class MockLocalStorageService {
setItem() {}
getItem() { return []; }
}
export class MockRouterEventService {
endEvents() {
return of({url: 'test/redirect', urlAfterRedirects: 'test/test'})
}
}
describe('The LoggingService', () => {
let mockStorage = new MockLocalStorageService();
let mockRouterEventService = new MockRouterEventService();
beforeEach(() => {
spyOn(mockStorage, 'getItem');
spyOn(mockStorage, 'setItem');
spyOn(mockRouterEventService, 'endEvents').and.callThrough();
});
beforeEach(() => TestBed.configureTestingModule({
providers: [
{ provide: LocalStorageService, useValue: mockStorage },
{ provide: RouterEventService, useValue: mockRouterEventService },
LoggingService
]
}));
it('should exist', inject([LoggingService], (loggingService : LoggingService) => {
expect(loggingService).toBeDefined();
}));
it('should retrieve previous history from localStorage', inject([LoggingService], (loggingService : LoggingService) => {
expect(mockStorage.getItem).toHaveBeenCalledTimes(1);
expect(mockStorage.getItem).toHaveBeenCalledWith('history');
}));
// etc
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment