【问题标题】:No Code Coverage for Fastify Integration Tests Using NYC/Istanbul written in Typescript使用 Typescript 编写的使用 NYC/Istanbul 的 Fastify 集成测试没有代码覆盖
【发布时间】:2020-06-29 14:29:28
【问题描述】:

我目前正在尝试使用 Mocha 和 NYC 在我的 fastify 路线上获得代码覆盖率。

我已经尝试预先检测代码,然后对检测代码运行测试,并尝试以各种方式设置 NYC 以使其正常工作。

这是我当前的配置。所有以前的都产生相同的代码覆盖率输出):

纽约配置

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

路线文件:

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

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

集成测试:

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);
  });
});

我的单元测试调用如下所示:

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

我只为const routes = 获得了 5% 的代码覆盖率。我真的很想弄清楚这一点。任何帮助将不胜感激!我在这里调查过的其他解决方案都不起作用。

【问题讨论】:

  • 我也很想知道这个问题的答案。我有一个非常相似的问题。

标签: mocha.js code-coverage istanbul fastify nyc


【解决方案1】:

我有一个 typescript + mocha + nyc 的详细示例。它还包含 fastify 测试,包括路由测试(注入)以及使用 sinon 的 mock + stub 和 spy 测试。所有异步等待也是如此。

它使用所有现代版本,还涵盖未使用的文件以及 VsCode 启动配置。欢迎在这里查看:

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

特别是我认为

instrumentation: true

弄乱了结果。这是我的工作 .nycrc.yml

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

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

在我上面提到的例子中,即使是模拟的 fastify 的 ans tub 部分,我也有适当的覆盖。

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2016-02-29
    • 2019-12-14
    • 2015-08-04
    • 2018-05-21
    相关资源
    最近更新 更多