Test Driven Development (URL Shortner App)

Never done a Test Driven Development and only Read about it. I thought its about time to learn and try this so I created an empty GitHub Repo node-testing and initialized that as a empty node project commit.

In Test Driven Development We must write the Tests first and then later we start making the app which start fixing the test fails.

For this project I created a bare bone App

Added an index.js with

1
2
3
4
5
6
7
8
9
10
11
const express = require('express')
const app = express()
const port = process.env.PORT || 9999

app.get('/', (req, res) => {
res.send('URL Shortner UP')
})

const server = app.listen(port)

module.exports = { app, server };

So Wrote a simple test/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Importing superTest to make Request to the Express App
const { expect, assert } = require("chai");
let request = require("supertest");
let {app,server} = require("../index"); // to Have a express app copy.


describe("Index Test", function(){
it("Test The Get Route", async function(){
let res = await request(app).get("/");
assert.strictEqual(res.status, 200, 'Status is not 200');
assert.strictEqual(res.text, "URL Shortner UP", 'Body Should be `"URL Shortner UP"`');
})
it("Try Adding a New URL and Test for if That short URL is Redirecting", async function(){
let res = await request(app).post("/").send({"url":"http://shubhkumar.in"});
assert.strictEqual(res.status, 200, 'Status is not 200');
assert.hasAllKeys(res.body, ["url","shortURL"], 'Body Should have `url` and `shortURL` in Response');
// Check if that Short URL is Redirecting

res = await request(app).get(`/${res.body.shortURL}`);
assert.strictEqual(res.status, 302, 'Status is not 302');
assert.equal(res.status, 302, 'Status is not 302');
})
})

and updated package json to contain

1
2
3
4
"scripts": {
"test": "mocha --exit"
}
}

and running npm test we get error for the implementation

Lets try to fix this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

const express = require('express')
const app = express()
const port = process.env.PORT || 9999

app.get('/', (req, res) => {
res.send('URL Shortner UP')
})

app.post('/',(req,res) =>{
res.json({"url":"hello","shortURL":"hello"})
})

app.get('/:id',(req,res) =>{
res.redirect("http://google.com")
})

const server = app.listen(port)

module.exports = { app, server };

This Fixes the Test but The test is not really Fixed.

We also see that we don’t need shortURL but id there.

With Time Both the Code and Test should evolve and make sure the app is working as it is intended.

The Code is Present on Github

If you have any question or have suggestion comment here or check discussions

Author: Shubham Kumar
Link: https://f3v3r.in/node/tdd/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.