What's the best way to write integration tests for API calls?
Asked by
_folded receipt
Today, we faced a production issue linked to a function that chains multiple API calls. Despite having unit tests for each of these APIs passing, we encountered unexpected exceptions based on certain input combinations when the series of calls made their way back to the front-end. I'm curious about how to effectively write integration tests for this situation. Can we set up tests that call the actual APIs during our CI/CD pipeline? Also, how can we manage test data in the database for these tests, ensuring that no one accidentally disrupts it? By the way, I noticed that our current integration tests don't seem to be true integration tests since they're mostly using mocked APIs.
Answers
You might want to check out Mock Service Workers. They allow you to create a 'fake backend' that your API calls target, letting the front-end tests run as if they're hitting the real APIs, but with mocked JSON responses instead of actual database interactions. This keeps everything running smoothly without a real backend involved.
Reply to this answer
E2E integration tests can get pretty tricky and often require a lot of resources to set up. From my experience in finance, we would schedule all our testing environments ahead of time and manage database records, pushing data through manually to ensure everything works as expected.
Reply to this answer
Hereโs an idea I had: if you're testing JSON APIs, you could prepare JSON files that fit your spec. Both the backend and frontend can utilize the same files. This ensures that the response format remains consistent across the board.
Reply to this answer
If you're using real API calls for end-to-end integration testing, itโs vital to create specific database records beforehand for the scenarios you want to test. Also, implementing reset handlers can help you clean up after tests run. This would ideally be done in a dedicated test environment.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions