简体   繁体   中英

How to test an angular service function nested promises?

Heres what my service kind of looks like

TestService.initializeDefaults = function() {
        var qPromise = $q.defer();
        $q.all({localResource : localResource.fetch(),
                item : itemResource.fetch()}).then(function(directories){

            //stuff happens with directories
            $q.all({
                thing1 : anotherThingFetch.fetch(),
                thing2: someThingFetch.fetch(),
                thing3: thingFetch.fetch()
            }).then(function(funData) {
                //stuff happens with the data

                preventiveServicesService.fetch().then(function() {

                    //stuff happens
                });

            });
        }.bind(this));
        return qPromise;
    };

And Im attempting to use karma to test that all the functions within this initializeDefaults method have run. Meaning that essentially all the fetch's happened. Heres what I have that works in the test so far:

it("should initialize defaults (Scenario 1)", function() {

            service.initializeDefaults();

            rootScope.$apply();

            expect(localResourceMock.fetch).toHaveBeenCalledWith();
            expect(itemResourceMock.fetch).toHaveBeenCalledWith();

Well there are 2 ways you can go about this.

1) Use $httpBackend: use something like $httpBackend.expectGET('url1').respond(200, {}) and so on for all the $http calss you're making. Then call $httpBackend.flush() and it should execute all nested promises as well. Downside: This will execute all logic in the methods being invoked.

2) Use Jasmine spies: Do something like:

let deferred = $q.defer();
deferred.resolve(/*data you expect the promise to return*/); 
spyOn(localResourceMock, 'fetch').and.returnValue(deferred.promise);
spyOn(itemResource, 'fetch').and.returnValue(deferred.promise);

spyOn(anotherThingFetch, 'fetch').and.returnValue(deferred.promise);
/*And so on for all methods being invoked*/

// Invoke the method
service.initializeDefaults();

// Trigger digest cycle
rootScope.$digest();

/*Expect all the spies to have been called*/
expect(anotherThingFetch.fetch).toHaveBeenCalledWith(); // will now pass

Either of those will work. Your call. Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM