At Woovi we love GraphQL, but we also provide a Public REST API for our users.
Testing REST APIs are harder than testing GraphQL APIs because REST accept any kind of input, so you need to have better validations.
After writing What to test in the backend, I decided to bring some more practical examples of How
to test backend.
Testing a simple REST API
Let's create a basic test for Woovi most used Public REST API, POST /charge
POST /charge create an Instant Payment Request, given a correlationID
, our idempotency key, and a value it will return the Pix QRCode that can be read for the payer to pay for the request.
import request from 'supertest';
import app from '../app';
it('should return 200 when request body is corret', async () => {
// create fixtures
await createCompany();
const payload = {
correlationID: 'correlationID',
value: 10,
};
// make a POST request to /v1/charge endpoint
const response = await request(app.callback())
.post('/v1/charge')
.set({
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: authorization,
})
.send(JSON.stringify(payload));
// assert response status and body
expect(response.status).toBe(200);
expect(response.body).toMatchSnapshot();
// assert database modifications
});
`
Before calling our endpoint, we can create some database fixtures to simulate the test scenario. Then we call the endpoint using supertest
package. We assert the response status and body, and we can also assert some database modifications.
This is the happy case, where everything goes right. This is the simplest possible test, you can get more complicated as you test more edge cases and real world scenarios.
In Brief
Automated tests are the only way to move fast without breaking things. At Woovi we want both, we want to move as fast as we can, but we don't want to break anything for our users.
Always start with the simplest test scenario, and then go to more complex and edge cases ones.
Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.
If you want to work with us, we are hiring!
Photo by Christina @ wocintechchat.com on Unsplash
Top comments (0)