DEV Community

loading...

How do you test your REST API?

faraazahmad profile image Syed Faraaz Ahmad ・1 min read

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.

Discussion

pic
Editor guide
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

And don’t forget Postwoman

Collapse
bpedroza profile image
Bryan

Does postwoman have functionality for writing/saving tests similar to postman?

Thread Thread
katnel20 profile image
Katie Nelson

Yes it does.

Thread Thread
bpedroza profile image
Bryan

Awesome, would you mind expanding on that or linking to something that explains it? I couldn't find it in the UI.

Thread Thread
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
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 Author

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).

Collapse
ajeebkp23 profile image
Ajeeb.K.P

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