Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resolve async await inside a unit test - javascript

I have a lambda for which I'd like to write unit tests for. I'm using async await but I'm getting issues with resolve promises. I'd like to test the different conditions, how can I write the test to resolve and stop seeing the timeouts?

Thanks in advance.

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

--- unit

describe('tests', function() {

    describe('describe an error', () => {
        it('should return a 500', (done) => {
            handler('', {}, (err, response) => {
                expect(err.status).to.eq('failed')
                done()
            })
        })
    })

});

-- handler

export const handler = async (event, context, callback) => { 

 return callback(null, status: 500 )

})
like image 237
Jimi Avatar asked Sep 20 '17 12:09

Jimi


People also ask

How do you resolve a promise in jest?

You can also use the . resolves matcher in your expect statement, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail. return expect(fetchData()).

What happens if you use await inside a loop?

You need to place the loop in an async function, then you can use await and the loop stops the iteration until the promise we're awaiting resolves. You could also use while or do.. while or for loops too with this same structure.


1 Answers

Try following:

describe('tests', function() {
    describe('describe an error', () => {
        it('should return a 500', (done) => {
            await handler('', {}, (err, response) => {
                expect(err.status).to.eq('failed');
            })
            done();
        })
    })
});

or

describe('tests', function() {
    describe('describe an error', () => {
        it('should return a 500', async () => {
            const error = 
              await handler('', {}, (err, response) => Promise.resolve(err))
            expect(error.status).to.eq('failed');
        })
    })
});

Anyway, I think, you need to await your async handler...

like image 54
dhilt Avatar answered Oct 12 '22 12:10

dhilt