GPGVM
GPGVM

Reputation: 5619

Jasmine, Karma, Mocking a Promise Properly

One of my Angular liabilities is being very new so this question may have an answer and I just don't know the terminology to use....my apologies.

My service endpoint:

//Initializes loading sort device config when the page is loaded
checkSortCfg(forceReload?: boolean): Promise<void>
{
    ...snip....

    let promise = self.sortApiSvc.getOut()
    
    ....snip.... 
    return promise;

}

API Service that gets called above:

getOut(): Promise<string[]> {
    const url = this.uriService.getAppServerUri('...');
    return this.http.get<any>(url).toPromise();
}

My unit test, I am leaving out the before each etc. as that all seems to be functioning properly.

My mock of the API call:

sortApiServiceCallSpy = jasmine.createSpyObj("SortApi", ["getOut"]);
sortApiServiceCallSpy.getOut.and.callFake(function () {
        return {
            then: function (callback) {
                return callback([
                    { value: new Observable<string[]>((observer) => { observer.complete(); }).toPromise() }
                ]);
            }
        };
    });

When I run the test and debug my mock comes back as undefined

ReferenceError: promise is not defined.

let promise = self.sortApiSvc.getOut()

So I must have the mocked return value wrong.

sortApiServiceCallSpy.getOut.and.callFake(function () {
        return {
            then: function (callback) {
                return callback([
                    { value: new Observable<string[]>((observer) => { observer.complete(); }).toPromise() }
                ]);
            }
        };
    });

Upvotes: 1

Views: 927

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29715

You can simply try out the following to return the mock Promise.

sortApiServiceCallSpy.getOut.and.returnValue(Promise.resolve(value));

Upvotes: 2

Related Questions