How to properly test promises

1k views Asked by At

I have test in React app using Jest and React-testing-library:

it('promise test', () => {
    const promise = new Promise<string>(resolve => setTimeout(() => resolve('foo'), 1000))
    expect.assertions(1);
    expect(promise).resolves.toBe('foo');
});

If i run test I get message:

Error: expect.assertions(1)
Expected :1
Actual   :0 

My question is.. Why code in expect(promise).resolves.toBe('foo') is not called? How to test this async promise?

1

There are 1 answers

0
Ashwel On BEST ANSWER

Correct solution is: You must make anonymous function async and await on response.

it('promise test', async () => {
    const promise = new Promise<string>(resolve => setTimeout(() => resolve('foo'), 1000))
    expect.assertions(1);
    await expect(promise).resolves.toBe('foo')
});

or this way

it('promise test', async () => {
    const promise = new Promise<string>(resolve => setTimeout(() => resolve('foo'), 1000))
    expect.assertions(1);
    await promise;
    promise.then(value => {
        expect(value).toBe('foo');
    })
});