Mocking AngularJS module dependencies in Jasmine unit tests

If you want to mock a module that declare one or more services I have used this code: beforeEach(function(){ module(‘moduleToMock’); module(function ($provide) { $provide.value(‘yourService’, serviceMock); }); }); This is useful if the service you want to mock is also a service that you want to unit test (in another jasmine describe). The solution proposed by … Read more

Unit testing an observable in Angular 2

The correct way for Angular (ver. 2+): it(‘retrieves all the cars’, waitForAsync(inject([CarService], (carService) => { carService.getCars().subscribe(result => expect(result.length).toBeGreaterThan(0)); })); Async Observables vs Sync Observables It is important to understand that Observables can be either synchronous or asynchronous. In your specific example the Observable is asynchronous (it wraps an http call). Therefore you have to use … Read more

How to unit test a component that depends on parameters from ActivatedRoute?

The simplest way to do this is to just use the useValue attribute and provide an Observable of the value you want to mock. RxJS < 6 import { Observable } from ‘rxjs/Observable’; import ‘rxjs/add/observable/of’; … { provide: ActivatedRoute, useValue: { params: Observable.of({id: 123}) } } RxJS >= 6 import { of } from ‘rxjs’; … Read more

Any way to test EventEmitter in Angular2?

Your test could be: it(‘should emit on click’, () => { const fixture = TestBed.createComponent(MyComponent); // spy on event emitter const component = fixture.componentInstance; spyOn(component.myEventEmitter, ’emit’); // trigger the click const nativeElement = fixture.nativeElement; const button = nativeElement.querySelector(‘button’); button.dispatchEvent(new Event(‘click’)); fixture.detectChanges(); expect(component.myEventEmitter.emit).toHaveBeenCalledWith(‘hello’); }); when your component is: @Component({ … }) class MyComponent { @Output myEventEmitter … Read more