Dieses Blog durchsuchen

Samstag, 6. August 2016

javascript: setup unittesting with mocka and chai on a node.js module. Building a bridge



In our last post, we had setup a node.js module and a npm project.
On this project we now want to setup the enviroment for some unittesting.

Prerequisits

1) Node.js
2) Npm 
3) gitclient

If you did not follow the tutorial, you can checkout the project here:
Open a terminal and type:
$ git clone https://github.com/pboethig/starwarsNames.git
$ npm install

Otherwise:

Add unittesting libraries

At first we want to add 2 new node libraries "mocha" and "chai" to our project to bring the unittesting capabilities.

Open a terminal and navigate to your projectroot and type:
$ npm install --save-dev mocha chai

After that you have the 2 new libraries in your local/node_modules


Create a first dummy-test

- create a file named "index_test.js" in the folder "src"
- open this file in your IDE.  I am using vscode with node.js plugins for that.

In this testfile we add follwing code.

To explain the code. At first we are referencing the expect method to a local variable "expect". In the second line, we are referencing our main module file "index.js", which we want to test.

The next lines are our first simple test, in which we want to try, if the testframeworks are loaded correctly.

Enabling the test in you package.json


At next we have to extend our package.json to setup our testfile.
- open the package.json
- search the line:
"test": "echo \"Error: no test specified\" && exit 1"
and replace it with
"test": "mocha src/index_test.js -w"

This tells npm to start the testfile under "src/index_test.js" with_ the mocha library.

Run your first test


Now you can test that by executing.
$ npm test

in your projectroot.

Yeah your first test is running, if you see something like this:


Source: https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-setting-up-unit-testing-with-mocha-and-chai. Thanx Kent.C.Dotts for the great video.




Keine Kommentare:

Kommentar veröffentlichen