lambda-tester icon indicating copy to clipboard operation
lambda-tester copied to clipboard

"Expecting a result, but received an error" when using Promise returned from function

Open paul-uz opened this issue 5 years ago • 1 comments

I am calling a function which returns a Promise, but it isn't working.

This works:

const self = {
    handler: (event, context, callback) => {
        return Promise.resolve(true).then((response) => {
             callback(null, {success:response})
        });
    }
}

module.exports = self

This doesn't

const self = {
    handler: (event, context, callback) => {
        return self.foo().then((response) => {
            callback('null', {success:response})
        })
    },
    foo: () => {
        return Promise.resolve(true)
    }
}

module.exports = self

My test:

it('Checks foo', () => {
        return lambdaTester(index.handler).event({foo: 'bar'}).expectResult((result) => {
            expect(result.success).to.equal(true)
        })
    })

paul-uz avatar Nov 03 '20 12:11 paul-uz

I think mixing callbacks and promises is not the best thing to do - I would suggest returning a Promise from the handler.

The reason why your second example fails because you're passing a string ('null') instead of null. AWS lambda accepts non-null values as the first parameter of callback() to trigger the error case.

So your first handler (the one that works) would look like:

const self = {
    handler: (event, context, callback) => {
        return Promise.resolve(true).then((response) => {
            return { success: response };
        });
    }
}

module.exports = self

A cleaner way might be:

const self = {
    handler: async (event, context) => {

        // do async stuff here
        const response = await Promise.resolve( true );

        return { success: response };
    }
}

module.exports = self

richardhyatt avatar Nov 03 '20 15:11 richardhyatt