Test that a function calls another function with Mocha

Problem

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?

Problem courtesy of: amandawulf

Solution

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

Solution courtesy of: amandawulf

Discussion

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:

Discussion courtesy of: Alfred

This recipe can be found in it's original form on Stack Over Flow.