How to validate that an API aligns with the database?
When developing software, the alignment between APIs and databases is crucial to maintain the integrity of the system. Throughout this class, we have learned how to perform tests that ensure that what an API returns is consistent with the information in the database. Imagine you have a payment system: the API must return amounts that match those stored in the database and in the proper format, such as adding a currency sign. This type of testing is essential to ensure that the software can be trusted.
How to implement joining API and database tests?
The class focuses on uniting knowledge of API and database testing. We will perform a step-by-step exercise on how to delete a record in the database using an API to validate its operation.
Creating the test environment
Before proceeding, it is essential to make sure that the server is running. If it is not, you can start it with the command configured in the package.json
file. Now, let's create a new test called 'joining all'.
describe('joining all', () => { it('should delete a record', () => { cy.request({ url: '/employees/3', method: 'DELETE' }).then((response) => { expect(response.status).to.equal(200); });
cy.task('queryDb', 'SELECT * FROM employees WHERE id = 3').then((results) => { expect(results.length).to.equal(0); }); }); }); });
Using plugins for queries
Once the entry has been deleted using the API, it is crucial to check the database to confirm the deletion. This is where custom plugins come in handy, such as the queryDb
plugin example.
Creating dynamic requests
Flexibility is key when creating tests. You can use string interpolation to handle IDs dynamically, avoiding static code in test environments:
const employeeId = 3;
cy.request({ url: `/employees/${employeeId}`, method: 'DELETE'}).then(response => { expect(response.status).to.equal(200);});
What challenges should you explore?
Implementing what you have learned in more complex scenarios is an effective way to consolidate your skills. Here are some challenges:
- Create a record in the database and store its ID in the context using an alias.
- Test the consistency between what the API returns and what you stored in the database.
- Develop methods that work for non-relational databases.
- Expand these examples to more complicated scenarios and share your learnings and experiences, encouraging knowledge sharing among developers.
Proper integration and validation between APIs and databases is essential for the development of robust and reliable software. Keep learning and sharing your knowledge!
Want to see more contributions, questions and answers from the community?