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

2

5

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.

Roadbed answered 14/1, 2020 at 11:25 Comment(0)
D
7

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));
    );
});
Desultory answered 14/1, 2020 at 11:58 Comment(1)
Thanks, this helped. I already tried this before but did not remove fakeAsync and then it did not work.Roadbed
D
0

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);
});
Drisko answered 28/2, 2023 at 20:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.