dwyl / aws-sdk-mock

:rainbow: AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!
Apache License 2.0
1.1k stars 108 forks source link

question/help: Confused about mock when using .promise() #215

Open ryanhuff opened 4 years ago

ryanhuff commented 4 years ago

I'm using

let promise = dynamodb.get(...).promise()

and

let promise = lambda.invoke(...).promise()

I'm not seeing how to mock "DynamoDB.DocumentClient.prototype" and "Lambda.prototype" so that I get back a "promise" method whose return value I can manipulate... help?

... in fact, i was able to get DynamoDB stubbed out ok with sinon directly, but the same approach didn't work with Lambda...

sandbox = sinon.createSandbox()
update_stub = sandbox.stub(AWS.DynamoDB.DocumentClient.prototype, 'update').returns({
  promise: () => Promise.resolve(update_meeting_result)
})

lambda_stub = sandbox.stub(AWS.Lambda.prototype, 'invoke').returns({
  promise: () => Promise.resolve({lambda_invoke_result}) // 
})
jcald1 commented 4 years ago

@ryanhuff , I also have the same issue so I opened https://github.com/dwyl/aws-sdk-mock/issues/217.

I just ended up mocking out the whole module that uses AWS, but this approach below might work for you. It worked for me in a small repro. If your use of aws-sdk is in a separate module, you'll need the @global': true option. If/when you get this working, you can then try adding in sinon.

const AWS = require('aws-sdk');

const handler = () => {
    console.log('1. AWS', new AWS.Lambda().invoke);
}

module.exports = handler;

Test:

const proxyquire = require('proxyquire');

const awkMock = {
    Lambda: function Lambda() {
        this.invoke = () => ({
            promise: () => Promise.resolve({})
        })
    },
    '@global': true
}

describe('file storage', () => {
    it('should handle an error emitted by the Readstream', async () => {
        const lambdaMocked = proxyquire('../index.js', { 'aws-sdk': awkMock});

        lambdaMocked()

    })
});