Failure of Angular $ windows in unit test cases

I am trying to run a unit test my angular user service written in Typescript. The service reads the global variable defined in the Window object. I promised, so in the future I can call AJAX to get this information. Here is my stripped-down 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;
    };

}

My 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();
        });
    });
});

Here are my questions: -

  • My test case is running, but I don’t see a mocking window in the service?

  • Is my promise or catch clause never kept?

  • Are there any more efficient ways to implement my service? I intend to return the promise, in the future I can use the AJAX call.

+4
source share
1 answer

$provide, unit test:

beforeEach(() => {
    module('myApp', ($provide) => {
      $provide.value('$window', myMockedWindowObject)
    });
});

$rootScope.$apply(), promises .

+5

All Articles