Running a local server and API testing in less than 10 mins ๐Ÿ˜ฎ

millankaul

Millan

Posted on September 18, 2021

Running a local server and API testing in less than 10 mins ๐Ÿ˜ฎ

Time is money ๐Ÿ’ฒ

So in next 10 minutes or less ๐Ÿคž I promise, we will:

  1. Start an API server on your machine (localhost)
  2. Run independent API test on โ˜๏ธ server.
    • Test's include assertion

โœ”๏ธ All this without using any dependency !!! โœ”




+                      Time starts now โฑ๏ธ


Enter fullscreen mode Exit fullscreen mode

ten minutes timer

Fig.1 - 10 minute timer

Step 1 : Set up the node / NodeJS

๐Ÿ’ก Think of NodeJs like JVM if you are familiar with java

If you already have it setup then you can jump to Code and run

Go to nodejs.org and download / install NodeJs on your platform. You may also Check their official Releases page

macos users : brew install node
linux users : sudo apt install node

Check installation by running this node -v on your terminal / cmd and you will see :



node -v
v16.8.0


Enter fullscreen mode Exit fullscreen mode

Version 16 was the latest while writing this article.

โ˜‘๏ธ And that's all you need today in terms of setup



Run and Test in 4 simple steps

1๏ธโƒฃ Setup server โœ”๏ธ
2๏ธโƒฃ Run server ๐Ÿƒ๐ŸŽฝ
3๏ธโƒฃ Write tests ๐Ÿ“
4๏ธโƒฃ Run API test's ๐Ÿš€

To keep it simple, we will keep server and test files in the same folder/directory.

So lets create a folder named dev on Desktop



Desktop/dev


Enter fullscreen mode Exit fullscreen mode

Let's Start ๐Ÿ‘‰ !



1๏ธโƒฃ Setup serverโœ”๏ธ

Go to dev folder (cd Desktop/dev) and create a file named server.js and copy this code:



//server.js

const http = require("http");

const HOST = "localhost";
const PORT = 8020;

const server = http.createServer(async (req, res) => {
console.log("Request on server received :  " + req.method + " : " + req.url);

  /**
   * Health check endpoint `/health`
   * 
   * @path {HOST}:{PORT}/health
   * @return status : {200}
   * @return message : text : "If you see this message, your API server is all set , Welcome !"
   */
  if (req.url === "/" && req.method === "GET") {
    // set the status code, and content-type
    res.writeHead(200, { "Content-Type": "application/json" });
    // send the response data as text
    res.end("If you see this message, your API server is all set , Welcome !");
  } 


  /**
   * Health check endpoint `/health`
   * 
   * @path {HOST}:{PORT}/health
   * @return status {200:OK}
   * @return uptime : how long has been server up & running
   * @return timestamp : Time of response from server  
   */
  else if (req.url === "/health" && req.method === "GET") {
    const healthcheck = {
      uptime: process.uptime(),
      message: "OK",
      timestamp: Date.now(),
    };
    res.end(JSON.stringify(healthcheck));
  } 


  /**
   * Endpoint not implemented / invalid endpoint
   * @path {optional} `/`
   * @return {404} - Route is not implemented (Page Not Found)
   */
  else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(
      JSON.stringify({ message: "Route is not implemented" })
    );
  }
});

server.listen(PORT, () => {
  console.log(`server started on : ${HOST}  port: ${PORT}`);
});


Enter fullscreen mode Exit fullscreen mode

So we โ˜๏ธ we created a server which will run (in next step) on . We have created these 2 endpoints:



http://localhost:8020/        //Base url : GET Home Page
http://localhost:8020/health  //Health   : GET server status


Enter fullscreen mode Exit fullscreen mode



Next ๐Ÿ‘‰ !



2๏ธโƒฃ Run server๐Ÿƒ๐ŸŽฝ

Open your terminal/cmd and navigate to Desktop/dev



cd ~/Desktop/dev 


Enter fullscreen mode Exit fullscreen mode

and run your server using this command:



node server.js


Enter fullscreen mode Exit fullscreen mode

If you see this message, it means your API Server is all set !


server

Fig.2 - server started on http://localhost:8020


You can even check it on your browser:

server verified on browser

Fig2.1 - server ( http://localhost:8020) accessible on browser




Next ๐Ÿ‘‰ !



3๏ธโƒฃ Write tests ๐Ÿ“

Under same folder Desktop/dev now create a file named test.js and copy this code:



//test.js

const http = require('http');
const assert  = require("assert");

let BASE_URL = "http://localhost:8020";


  /**
   * Test 1 : Hit BASE_URL and assert response statusCode to be  === 200
   * 
   * @path {BASE_URL}
   * @return expect : {200}
   */
http.get(BASE_URL, (response) => {
      console.log("Response: " + response.statusCode);
      assert(response.statusCode === 200);
    });

  /**
   * Test 2 : Hit `/health` endpoint and assert response statusCode to be  === 200
   * 
   * @path {BASE_URL}/health
   * @return status : {200}
   */
http.get(BASE_URL+'/health', (response) => {
      console.log("Response: " + response.statusCode);
      assert(response.statusCode === 200);
    });


  /**
   * Test 3 : Hit random endpoint `/thisIsNotAValidEndpoint` and assert response statusCode to be  === 404
   * 
   * @path {BASE_URL}/thisIsNotAValidEndpoint
   * @return status : {404}
   */
http.get(BASE_URL+'/thisIsNotAValidEndpoint', (response) => {
      console.log("Response: " + response.statusCode);
      assert(response.statusCode === 200);
    });


Enter fullscreen mode Exit fullscreen mode

Next ๐Ÿ‘‰ !



4๏ธโƒฃ Run API test's ๐Ÿš€

โ€ผ๏ธ Make sure you open a new terminal/cmd window to run this and also be sure that our server is still running (step 2๏ธโƒฃ Run server๐Ÿƒ๐ŸŽฝ ) on separate terminal/cmd.



node test.js


Enter fullscreen mode Exit fullscreen mode

you will see something like this



dev $ node test.js 
Response: 200
Response: 200
Response: 404
node:assert:400
    throw err;
    ^

AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

  assert(response.statusCode === 200)

    at ClientRequest.<anonymous> (.../Desktop/dev/test.js:40:7)
    at Object.onceWrapper (node:events:514:26)
    at ClientRequest.emit (node:events:394:28)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:621:27)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
    at Socket.socketOnData (node:_http_client:487:22)
    at Socket.emit (node:events:394:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10) {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '=='
}


Enter fullscreen mode Exit fullscreen mode

WHATโ—

What just happened โ— , why all these logs are printed.

๐Ÿ˜„ Well it is expected, here is why โฌ‡๏ธ

In the above test.js this was intentionally put to demo, what will happen when an test fails on assertion.

Troubleshooting : Start by reading error printed:



AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

  assert(response.statusCode === 200)


Enter fullscreen mode Exit fullscreen mode

It is trying to tell you that, the expected response code 200 was not received.

Que: But which one ??

Answer : Read just 1 more line from logs it tells you exactly where test.js:40:7



 at ClientRequest.<anonymous> (.../Desktop/dev/test.js:40:7)


Enter fullscreen mode Exit fullscreen mode

Let's Fix this :

  • Open test.js in your text editor.
  • Go to line # 40


assert(response.statusCode === 200);


Enter fullscreen mode Exit fullscreen mode

Change 200 to 404



assert(response.statusCode === 404);


Enter fullscreen mode Exit fullscreen mode

now save and close this file.

Self assignment: Try to explore the reason yourself.
hint: line # 33 of test.js


Let's try to run test's once again ๐Ÿƒ ๐Ÿš€



node test.js

Enter fullscreen mode Exit fullscreen mode




Done !

successful test run

Fig.3 - Successful Test run โœ”๏ธ

1 second left on timer

Fig.3.1 - Time over

Hope you enjoyed my first article on dev.to ๐ŸŽ‰

Credis: API icon by Icons8

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
millankaul
Millan

Posted on September 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About