Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that a function calls another function with Mocha

I have a question about testing a specific situation in Mocha for Node.js. Suppose I had the following code in my app...

function a() {
     //...
}

function b() {
    //...
}

function c() {
    if(condition) {
         a();
    } else {
         b();
    }
}

If I were testing function c, how could I verify that function a or function b got called? Is there a way to do this?

like image 895
amandawulf Avatar asked Jun 21 '12 23:06

amandawulf


2 Answers

I found a solution for what I was trying to do. Sinon spies can help determine whether a certain function was called or not.

like image 110
amandawulf Avatar answered Sep 23 '22 10:09

amandawulf


That is what code coverage is for. Luckily mocha has support for that leveraging JSCoverage. I use a MakeFile that looks like:

coverage:
    rm -rf lib-cov
    jscoverage --no-highlight lib lib-cov
    @MOCHA_COV=1 mocha --reporter html-cov > coverage.html
    google-chrome coverage.html
  1. The first line removes (previous) instrumented javascript files(folder) needed for Mocha to display code coverage.
  2. Second line uses jscoverage to created instrumented lib-cov folder from original lib folder.
  3. Third line is used to make sure that my node code knows it needs to run instrumented code.
  4. Finally I view coverage.html in google-chrome.

In my mocha test file I have a line that looks like:

var BASE_PATH   = process.env.MOCHA_COV ? './../lib-cov/' : './../lib/';

That way when MOCHA_COV=1 then the instrumented code will be used.


Some more interesting links about code coverage:

  • http://tjholowaychuk.com/post/18175682663/mocha-test-coverage
  • http://www.seejohncode.com/2012/03/13/setting-up-mocha-jscoverage/
like image 41
Alfred Avatar answered Sep 22 '22 10:09

Alfred