Testing promise in Angular 2 ngOnInit

IMO the best solution for this use case is to just make a synchronous mock service . You can’t use fakeAsync for this particular case because of the XHR call for templateUrl. And personally I don’t think the “hack” to make ngOnInit return a promise is very elegant. And you should not have to call … Read more

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 Isolated Scope Directive in AngularJS

See angular element api docs. If you use element.scope() you get the element’s scope that you defined in the scope property of your directive. If you use element.isolateScope() you get the entire isolated scope. For example, if your directive looks something like this : scope : { myScopeThingy : ‘=’ }, controller : function($scope){ $scope.myIsolatedThingy … Read more