Background

I could find lots of examples of mocking the AWS-SDK. But I have been finding it complex. I have been exploring some other approach that it will be easier to mocking AWS-SDK.

Outlines

  • Eventually, AWS-SDK is a wrapper of WebAPI. All functions contain in a services object.
  • For keeping versatility, each service has versions of API
  • When a service instance created, the latest service is called from inside SDK.

Thus backdoor approach, We can mock only specified aws-sdk functions.

Example(Lambda Invoke)

example.test.ts

import * as AWS from 'aws-sdk'
jest.spyOn(AWS.Lambda.services ["2015-03-31"].prototype, 'invoke').mockImplementation( (request) => {
    return {promise: () => 'debug'}
})
  • many cases, the promise method seem to be called. Return an object which includes the promise method.
  • spyOn is helpful. because it’s easy to restore the mock by calling jest.restoreAllMocks()

Conclusion

I think this is helpful. You don’t have to add another package, You don’t have to make a wrapper class of AWS-SDK for achieving testable. many cases, to keep testability, these wrapper class inserted as a parameter of constructer. (Dependency Injection)

Categories: Others

Leave a Reply

Your email address will not be published. Required fields are marked *