Using frameworks

There are a couple of test frameworks available for Node.js. What they do is give you an environment where you can focus on the test cases. Some frameworks will even do code coverage more or less automatically.

One of the most commonly used frameworks is mocha, which is a simple yet powerful framework. It can be used for general unit testing, but also for performance, as it is able to highlight slow tests.

Let's try it out and prepare our microservice for the tests. You can use any of the previous versions; it should not matter for the storage model we're using, only the microservice interface. First of all, let's install mocha as a development dependency. We're also using an assertion library called chai, which has a plugin specifically for HTTP testing:

npm install –save-dev mocha chai chai-http

Then, change your package.json file to update the scripts part to something similar to this:

"scripts": {
"test": "node test/run"
},

This tells NPM that, to test our microservice, it should run the node test/run command. We now need to create this file (test/run.js) so it will actually work. Create the test folder, add the run.js file, and add only this line to it:

console.log("ok");

Now, go to a console on our microservice folder and run the test command:

npm test
> [email protected] test /Users/dresende/imagini
> node test/run

Ok

The first step is complete. This is not actually a test, but we now have the initial structure.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset