Klyner
Klyner

Reputation: 4163

How can I let Jasmine wait for a promise to be resolved or rejected?

I have a particular function that I am trying to test using Angular. This function returns a promise. Although in my test I set expectations for the promise result, Jasmine does not wait for the promises to be resolved or rejected.

Warning:

ERROR: 'Spec 'test' has no expectations.'

The tested function is defined like:

public validate(file: File): Promise<any[]> {
    return new Promise((resolve, reject) => {
      // Code
    }
}

The test code:

it(
    test.description,
    fakeAsync(() => {
      // Doesnt wait for the following promise result:
      importValidator.validate(test.testFile).then(
        resolveValue => {
          expect(Array.isArray(resolveValue)).toBe(true);
        },
        onReject => {
          expect(test.resolve).toBeFalsy();
        }
      );
    })
  );

How can I let Jasmine wait during the tests for the validation promise to be resolved/rejected? When I let the test fail by expected something not happening, it actually throws an error in the afterAll.

Upvotes: 5

Views: 9137

Answers (2)

Rich Finelli
Rich Finelli

Reputation: 907

Avoid fakeAsync() unless you're testing setTimeout() and anything else where time is involved. For promises, especially API requests, try making the it() block async/await as this is closer to the way you are writing your promise. While you're at it, making the function use async await isn't a bad idea either (but not necessary).

public async validate(file: File): Promise<any[]> {
    let myArray = await this.myService.validate(test.testFile);
    return myArray;
}

it('should return array', async () => {
    let expectArray = [
        // define your array here...
    ];
    let resolveValue = await importValidator.validate(test.testFile);
    expect(resolveValue).toEqual(expectedArray);
});

Upvotes: 0

uminder
uminder

Reputation: 26150

As explained at https://jasmine.github.io/tutorials/async, there exist different ways to test asynchronous code with Jasmine.

One possible way is to use the done function.

it('#validate should return array', (done) => {
    importValidator.validate(test.testFile)
        .then(resolveValue => {
            expect(Array.isArray(resolveValue)).toBe(true);
            done();
        })
        .catch(err => fail(err));
    );
});

Upvotes: 7

Related Questions