Simple TDD in NodeJS with 5 Steps

Jeff Simons Decena
3 min readJul 5, 2020

--

You need to start TDD in NodeJS right now! Some asks why? I ask, why not?

I started writing the TDD in Laravel — currently the most famous PHP web framework, with simple instructions on how to start a PHP programmer’s test driven development journey. Now, I would like to share how we can have the same pattern in NodeJs.

In any programming language, test driven development can be really daunting. But, if you put your heart to it and think of the future of the project for both the maintainers and yourself, you would persevere into always put a test in every bit of code you put into your application.

For this tutorial, I will use AdonisJS framework which is very similar to Laravel in code structure. Once installed, run npm install to install the needed libraries.

Set up the test environment

Step 1

You need to set up the TEST environment for AdonisJS for it to work — Set up the test here. Once set up, you can run adonis test to run the default test.

info: serving app on http://127.0.0.1:4000Example
✓ make sure 2 + 2 is 4 (2ms)
PASSEDtotal : 1
passed : 1
time : 6ms

Create your first test case

Step 2

Let us, create our own test. In the example.spec.js , just rename the test name from make sure 2 + 2 is 4 into it can make a user.

With the above code, we just simply imported the User model and created a random data object that we passed on the create method on the User model.

If we run adonis test and we will get:

info: serving app on http://127.0.0.1:4000User unit test
✖ it can make a user (8ms)
ERRORS1. it can make a user
expected 'johndoe' to equal undefined
"johndoe" => undefined

--

--

Jeff Simons Decena

Senior Fullstack Engineer, React Native developer and HL7 Health Informatics professional

Recommended from Medium

Lists

See more recommendations