DEV Community

Syed Faraaz Ahmad
Syed Faraaz Ahmad

Posted on

How do you test your REST API?

I have a basic REST API in a server file. If I want to run tests on the routes, how do I do so?

I can think of 2 ways to do so:

  1. In the test command, first start the server using a child process and then send requests to localhost in the unit tests.

  2. Write unit tests for all the functions I've written in my code and run them without running the server (Does this mean I can't do integration testing?)

I'm really not sure what to do, I need help.

Top comments (10)

Collapse
 
likelocusts profile image
LikeLocusts

Did you have a look at Postman? It's a really helpful tool for testing your API. It enables you to do integration testing

Collapse
 
katnel20 profile image
Katie Nelson • Edited

And don’t forget Postwoman

Collapse
 
jhechtf profile image
Jim Burbridge

Tests

Well, I use Fastify most times for APIs and it has a nice method called inject, which is mostly just used for testing. The setup ends up looking something like

// server.js
const Fastify = require('fastify');
const app = Fastify();

app.get('/some-route', async () => "data");

app.listen(3000, err =>  {
  if(err) { console.error(err); process.exit(); }
  console.log('listening');
});

module.exports = app;

// main.test.js
const test = require('ava');
const app = require('../server.js');

test('API Testing', async t => {
   await app.inject({ url: '/some-route' })
     .then(res => { t.is(res.statusCode, 200); })
     .catch(err => t.fail());
   });
});

(note: roughed most of this from memory so it might not be 100% runnable).

Otherwise

Most people use something like Postman. I've switched over to the Insomnia REST client.

Collapse
 
crewsycrews profile image
🎲Danil Rodin🎲

The good alternative to Postman is a TestMace. I liked the way they looking at the testing environment as a filesystem project, so you can easily version control it and share across your team.

Collapse
 
devdrake0 profile image
Si

What language are you using?

Collapse
 
faraazahmad profile image
Syed Faraaz Ahmad

I'm using Rust (for learning purposes)

Collapse
 
devdrake0 profile image
Si

ah ok - have a look for a rust-alternative to supertest (Javascript) or net/http/test (Go).

 
katnel20 profile image
Katie Nelson

Yes it does.

 
katnel20 profile image
Katie Nelson

Yes, take a look at the history and collections tabs.
Make a request, and click on the 'Save to collections' button (it looks like a disk).

Collapse
 
ajeebkp23 profile image
Ajeeb.K.P

Check my blog article about Requester (A sublime add-on). dev.to/ajeebkp23/requester-modern-...