Before going to the detail, let’s me share a little bit about our system - we’re using Elixir-Phoenix framework to build a backend system and from the requirement, we need to build an API that can support our front-end client (ReactJS/React-Native) upload files to AWS_S3.
In Phoenix framework, we used an AWS client’s hex package called ex_aws to upload files to S3. Basically, the controller code will be:
ExAWS.request!() will return the status_code is 200 if uploading is successful, otherwise, it will return another status_code.
Uploading module
As usual, we moved uploading code from UploadController to a UploadService module - this will make the controller looks more readable and easy to write the test.
When integrating with external services we want to make sure our test suite isn’t hitting any 3rd party services. Our tests should run in isolation. ThoughBot
With our UploadService module, we don’t need to test the request to S3 because the package itself already test. So, we only need to mock module to return ok or error response.
Setup the corresponding modules for different environments
The development and production environment will use the real UploadService and test environment will use the UploadService.Mock.
1 2 3 4 5
# dev.exs and prod.exs config :my_app, :upload_service, UploadService
This is the way how we write test for API without hitting to external services. It could not a good way, so if you guys have any idea, fell free to comment.