Table Of Contents
What is Unit testing ?!
Is a software testing method by which individual units of source code and typically automated tests written and run by software developers to ensure that a section of an application (known as the "unit") meets its design and behaves as intended.
Why using Unit testing
Testing is one of those things that people either love or hate. Usually testing is something that is hated
Until you work on a project with good tests and you realize how amazing they are.
At the end of the article I will breakdown the importance of testing and some best practices you can adhere to in order to make your tests amazing.
Who use Unit testing ?!
To get started in this trip, I have simple REST APIs already created (Get, Post, etc.)
And these are very simple server-side Nodejs with Express APIs GitHub repository link
in our case we have a route get all tasks which response with a small array of tasks.
Chai is an assertion library for NodeJS and browser with three styles [ should, Expect, Assert]
1.In order to start this all we need to do is to install two libraries with
run npm i mocha chai --save--dev
2.Now that is done downloading we come here where we have test script and we can change this by typing in
3.So to get started creating first test all need to do is create folder called test and add a new file task.js give it the exact same name as file you want to test in our case we will test
4.Now inside this file all need to do to import routes file (task.js) including all APIs and in order to write test we need to import chai then adding Assertion
5.Now we are able to call our RESTful APIs and in order to use mocha describe our test let's call it
tasks API, then we define an arrow function so first task to describe Get API let's call it
Get-All-Tasks then user It to describe what our API do
it should Get all the tasks
6.Here we use chai with
chai.request(server) and test our Get API
.get("/api/tasks") the we expect using
.end((err, response) which will receive error and response so we expect a successful results so response should have status 200 and body should be an array with 3 tasks
Done(), and run using
npm test and the test run successfully
If you need to request wrong route to show API response we make small changes
Test the GET (by Id) route the same steps but we will add task id and in response we will check for returned properties
Testing one of the most important skills you can known as a developer, It's something a lot of people don't teach or focus on but if you known testing, It's gonna set you apart from every other developers that doesn't known testing and give you extra leg up when you applying for jobs