Writing Unit Test Cases in Node.js
In writing unit tests, you may need a framework of two main packages, one is Mocha and the other is Chai. These frameworks allows you to break and test segments of your project.
Mocha packages is installed by simply running npm install mocha –g. It then gives you options of selecting your favorite assertion libraries. On the other hand, Chai is installed by first creating a package.json file then running the installation command. Common assertion libraries include the expect, should and assert. I am going to use a step by step approach in my illustration
In setting a simple test in Node.js, you can make a folder in your project root and name it test’. At that point inside that folder, include a file and name it test-server.js.
Then add your code into this new file. Your code should be a test to the it() and dexcribe() statements. describe() is utilized for gathering tests in an intelligent way. In the mean time, the it() proclamations contain every individual testing, which by and large (err, should) test a solitary component.
This is well done by utilizing the Chai package. The biggest advantage with Chai is that it permits you to pick the kind of statement style you’d get a kick out of the chance to utilize. In this case chai, chai-http and the already created tesr-server.js file which utilizes the should assertion in make a request.
Testing GET Logic
You require to first make an update to the it() statement to start with. In most cases, the done() argument which terminates your test case if called. You then need to run the Mocha package which offers the test output. The code involves a simple GET request for the /blobs terminal. An assertion is then made that the reaction contains these 200 http status code.
Testing POST Logic
This is meant to show whether a new blob gets successfully added. In most cases, a message of success should be the output
Utilized in adding dummy databases. The afterEach() and beforeEach() are added to remove or add dummies to the database after or before an execution.
[vc_row][vc_column][td_block_21 separator=”” tag_slug=”node-js” limit=”40″ tdc_css=””][/vc_column][/vc_row]