Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I structure node.js mocha tests [closed]

I'm very beginner for unit testing in node.js, I want to know what is the best practice of writing unit testing in node.js for example 'it' method how many assert test cases I can have, Is there any standard of writing only one test case in single it method. Please give me an idea to write the unit test case. Thanks in advance.:)

like image 209
Veeresh Digasangi Avatar asked Oct 17 '15 04:10

Veeresh Digasangi


2 Answers

This free tutorial explains Chai and Mocha quite well, and how to structure it.

While Mocha is a regular test framework, Chai is an expectation framework. The key difference is syntactically sugary how tests are formulated (the use of it() for test cases), which I personally find confusing, too.

For a starter, you should probably stick with mocha. It might help you to get some wording straight:

  • Mocha is a test framework (so you have a defined outer set of functionality, in which to fill in the gaps, aka place your tests, etc), whereas
  • Unit.js is a test library, so it offers a bunch of functions (like all kind of asserts), but you are driving your script. (No test suites, test rnning)

The mocha.js framework uses the unit.js test functions (see here).

like image 29
Frank Nocke Avatar answered Oct 18 '22 08:10

Frank Nocke


Test one part of functionality in one it() call and only use multiple assertions if really needed.

If you use 2 assertions in one it() call, failure of the first one will block the second one from being executed, thus hiding part of your tests and therefore preventing you from getting a full view on a possible error.

Study how to use before/after and beforeEach/afterEach inside a describe block - those will really help you to only perform tests on small parts of your code in every it(). See the 'Hooks' chapter in the mocha documentation.

Optionally create your own set of helper functions to prepare set up your code for a single test to prevent (too much) code duplication in your tests - I believe code duplication in tests is just as bad as code duplication in your 'real' code.

like image 117
Simon Groenewolt Avatar answered Oct 18 '22 08:10

Simon Groenewolt