Attempting to unit test an angular custom service written in Typescript has been a challenge for me. The service is designed to read a global variable defined on the Window object and I have made it promise-based for potential future AJAX calls. Below is a simplified version of my service: -
export class ProxyDetectiveService {
public static $inject = [
$window,
$q
];
constructor(private $window:ng.IWindowService,
private $q:ng.IQService) {
}
public getProxyUserObject = ():ng.IPromise<any> => {
this.log.debug('Proxy User Service called, to get proxy user details');
var deferred = this.$q.defer();
var proxyDetails = this.$window.portalObject;
deferred.resolve(proxyDetails);
return deferred.promise;
};
}
Unit Test Case: -
describe('Proxy Detective Service - Unit Test Cases', () => {
var proxyDetectiveService:any,
$window:ng.IWindowService;
beforeEach(() => {
module('myApp');
});
beforeEach(inject(($injector:ng.auto.IInjectorService, _$window_) => {
proxyDetectiveService = $injector.get('ProxyDetectiveService');
_$window_ = {
portalObject: {
proxyUserDetails: {
firstName: 'testFN',
lastName: 'testLN'
}
}
};
}));
it('should have proxy object defined', function () {
var promise = proxyDetectiveService.getProxyUserObject();
promise.then(function (response) {
expect(response).toBeDefined();
}).catch(function (response) {
expect(response).toBeUndefined();
});
});
});
I have some questions regarding this setup: -
Even though my Test case runs, why can't I see the mocked window object in the service?
Why do my promise then or catch clauses never execute?
Are there better approaches to implementing my service? I aim to return a promise and potentially integrate AJAX calls in the future.