Dieses Blog durchsuchen

Samstag, 6. August 2016

javascript: unittesting with node.js, mocha and chai



In the  last post, we had setup a unittest enviroment for node.js with mocha and chai. Today we want to use it on our testproject

Prerequisits

You have to be installed:
Node.js
Chai.js
Mocha.js

Our project from the last post:
$ git clone https://github.com/pboethig/starwarsNames.git
$ npm install

Let's start


This was our code to test. File "src/index.js"
If you open that file, you see that we have 2 properties in our module. "starwarsNames" from type String Array and "random" from type Random String. Now we want to test this 2 types.

For that we implement a function "isTypeOfStringArray()" and the describe function to test that in our testfile under "src/index_test.js"

Here is my "src/index_test.js" You deeply understand how the testcode works, if you have a look on the chai documentation
 


Run the test

Now switch to your terminal and type:
$ npm t

This will launch the configured testfile "src/index_test.js".We have configured it in "package.json"

Now you should see something like that
 
 Great. The test was successful.

Let's create another test

Now we want to test, if "Luke Skywalker" is in the list with starwarsnames

I have added the new test to "src/index_test.js"
As you can see, I have added a second test to the describe "starwars-names" function. This tests uses "to.include()" to check the array for the string "Luke Skywalker". As you can see, you only need to save the testfile, and the test gets executed directly.

Kent You should now see a terminal like that:

Awesome. That it!


And now the final test

The last test, checks if the "random" function of our library gives us a random starwars-name from the list

I have added the test "should contain a random name from the list" to the tests.

Here is my final version of "src/index_test.js"
If you run the test, you should see 3 passed tests now
Thats all for now. Thanks to Kent.C.Dots for the great video:
https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-unit-testing-with-mocha-and-chai

Keine Kommentare:

Kommentar veröffentlichen