2

I'm currently trying to get code coverage on my fastify routes using Mocha and NYC.

I've tried instrumenting the code beforehand and then running the tests on the instrumented code as well as just trying to setup NYC in various ways to get it to work right.

Here is my current configuration. All previous ones produced the same code coverage output):

nyc config

"nyc": {
  "extends": "@istanbuljs/nyc-config-typescript",
    "extension": [
        ".ts",
        ".tsx"
    ],
    "exclude": [
        "**/*.d.ts",
        "**/*.test.ts"
    ],
    "reporter": [
        "html",
        "text"      
    ],
    "sourceMap": true,
    "instrument": true
}

Route file:

const routes = async (app: FastifyInstance, options) => {

  app.post('/code', async (request: FastifyRequest, response: FastifyReply<ServerResponse>) => {
    // route logic in here
  });
};

The integration test:

import * as fastify from fastify;
import * as sinon from 'sinon';
import * as chai from 'chai';

const expect = chai.expect;
const sinonChai = require('sinon-chai');
chai.use(sinonChai);

describe('When/code POST is called', () => {
  let app;

  before(() => {
    app = fastify();

    // load routes for integration testing
    app.register(require('../path/to/code.ts'));
  });
  after(() => {
    app.close();
  });

  it('then a code is created and returned', async () => {
    const {statusCode} = await apiTester.inject({
      url: '/code',
      method: 'POST',
      payload:{ code: 'fake_code' }
    });
    expect(statusCode).to.equal(201);
  });
});

My unit test call looks like the following:

nyc mocha './test/unit/**/*.test.ts' --require ts-node/register --require source-map-support/register --recursive

I literally get 5% code coverage just for the const routes =. I'm really banging my head trying to figure this one out. Any help would be greatly appreciated! None of the other solutions I have investigated on here work.

Christopher
  • 262
  • 2
  • 9

1 Answers1

0

I have a detailed example for typescript + mocha + nyc. It also contains fastify tests including route tests (inject) as well as mock + stub and spy tests using sinon. All async await as well.

It's using all modern versions and also covers unused files as well as VsCode launch configs. Feel free to check it out here:

https://github.com/Flowkap/typescript-node-template

Specifically I think that

instrumentation: true

messes up the results. Heres my working .nycrc.yml

extends: "@istanbuljs/nyc-config-typescript"

reporter:
  - html
  - lcovonly
  - clover
  # those 2 are for commandline outputs
  - text
  - text-summary
report-dir: coverage

I have proper coverage even for mocked ans tub parts of fastify in my above mentioned example.

Flowkap
  • 729
  • 6
  • 16