mercredi 4 février 2015

AngularJs unit test failing when calling $http

My controller is something like this (everything in typescript)



module testmod {
export class profileCtrl {
constructor(
public q: ng.IQService,
public scope: IProfileCtrlScope,
public state: ng.ui.IStateService,
private accountSvc: accountSvc) {
this.test();
}

public test(): ng.IPromise<boolean>{
var task = this.q.defer();
this.accountSvc.get()
.then((data) => {
this.scope.data = data; //data from service is "true"
task.resolve(true);
})
.catch((data) => {
task.reject(false);
});
return task.promise;
}


and my spec is



beforeeach(....) //set service, ctrl, scope etc here

spyOn(accountSvc, "get").and.callFake(function () {
console.log('*************************');
var deferred = q.defer();
deferred.resolve(true);
return deferred.promise;
});
it('should have valid profileCtrl', () => { //SUCCESS
expect(profileCtrl).not.toBeNull();
expect(profileCtrl).not.toBeUndefined();
});
it('should call get service', () => {
//http.expectGET('/api/get')
// .respond(true);

scope.test()
.then((data) => {
expect(scope.data).toBeTruthy() //FAILURE
})
.catch((e) => {
expect(false).toBe('true'); //CODE IS NOT REACHING HERE, SO ACCOUNTSVC CALL IS SUCCEEDING
});
//http.flush();
scope.$apply();
});


When unit testing this, i am seeing the "test" method is getting called many times and in many instances. Since I want to load some data when this controller is loaded (say the home page to fetch user details), that is why I put the "test" method in the constructor. When running the page normally, I don't see any multiple calls. I cannot put this in a service as this function will be called from many controllers and we need uptodate data and not any cached version.


I can see that the spyOn function is getting called, accountSvc is getting called, however the scope.data value is null. I even tried with httpBackend (commented code), still the scope.data is null. I have unit tests directly on the accountSvc service using httpBackend and they are working as expected. The failure is when I have a controller with a method in the construcotr. What am I doing wrong here? This is of course a simplified version of the app and calls. Appreciate any help on this.


Aucun commentaire:

Enregistrer un commentaire