node.jsexpresscode-coverageistanbulnyc

How to get code coverage of nodejs application without having to write test cases in recommended frameworks?


Its recommended to use frameworks like Mocha, chai or jest to make use of istanbul to get code coverage.

I have designed a testing tool, which will send a request to a api and based on the response, it will be termed as pass or fail.

The payload and the expected result is present in a excel sheet. For each row, it will send the payload present in the corresponding column and compares the response with the actual response we get. With this type of environment, will I be able to get the code coverage of my application.


Solution

  • nyc can instrument any node process (the more complex your build environment, the more complex the setup).

    nyc node server.js
    

    You just need a way to shutdown at the end of the tests.

    A conditional finalise route could be added

    if (process.env.NODE_ENV === 'test' ) {
      router.post('/shutdown', ctx => {
        database.close()
        server.close()
        ctx.body = 'Shutting down'
      })
    }
    

    Then run the test server via nyc

    yarn add --dev nyc
    NODE_ENV=test ./node_modules/.bin/nyc node server.js
    

    Then you get the report and a .nyc_output directory

    -----------|---------|----------|---------|---------|-------------------
    File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    -----------|---------|----------|---------|---------|-------------------
    All files  |   58.33 |      100 |      50 |   66.67 |                   
     server.js |   58.33 |      100 |      50 |   66.67 | 15-17             
    -----------|---------|----------|---------|---------|-------------------