如何为快递功能设置代码覆盖率和单元测试?

时间:2015-03-30 16:47:47

标签: node.js unit-testing express coffeescript mocha

我的路线定义为

app.post '/v1/media', authentication.hasValidApiKey, multipart, mediaController.create, mediaController.get

我想为路线的各个组成部分编写测试。所以从authentication.hasValidApiKey开始,这是另一个文件中定义的函数:

exports.hasTokenOrApi = (req, res, next) ->
  if not req.headers.authorization
    return res.status(403).end()

  doOtherStuff...

在我的测试中,我有:

authentication = require '../src/middlewares/authentication'

describe 'Authentication Middleware', ->
  before (done) ->
    done()

  it 'should check for authentication', (done) ->
    mock_req = null
    mock_res = null
    mock_next = null

    authentication.hasTokenOrApi mock_res, mock_req, mock_next
    done()

我如何处理req,res和next?我如何设置代码覆盖率来运行?我正在使用export NODE_ENV=test && ./node_modules/.bin/mocha --compilers coffee:'./node_modules/coffee-script/lib/coffee-script/register'

运行我的测试

1 个答案:

答案 0 :(得分:2)

有多种代码覆盖工具,其中很多都在不同的构建系统中集成(gulp,grunt等等)。

其中一个领先者是Istanbul,这是我个人使用的。其他受欢迎的图书馆是blanketscoveralls

要查看使用Gulp和Istanbul(以及mocha)的示例设置,请查看this gist I have

基本上,您可以运行测试目录,通过istanbul管理每个测试文件,然后通过mocha,并根据需要生成覆盖率报告。

gulp.src(['test/**/*.js'])
    .pipe(istanbul({includeUntested: true})) // Covering files
    .pipe(istanbul.hookRequire()) // Force `require` to return covered files
    .on('finish', function () {
        gulp.src(['test/**/*.js'])
            .pipe(mocha())
            .pipe(istanbul.writeReports(
                {
                    dir: './coverage',
                    reporters: ['html', 'lcov', 'json', 'text', 'text-summary', 'cobertura']
                })) // Creating the reports after tests runned
            .on('end', cb);
    });

关于如何仅测试路由(假设它在单独的文件或模块中解耦),这可能有点棘手。我发布了herehere类似的问题。

但基本上你在上面的代码中提出的要求是req的存根和res.status(403).end()的间谍。间谍可能有点棘手,因为你基本上需要监视Express中的实际Response对象(可以围绕他们的文档谷歌查看如何获得它)。

如果您还不熟悉,我建议使用sinon,但还有其他库用于模拟/存根/间谍。

社区中似乎很多人只是使用Supertest并称之为一天,但对我而言,这将使其成为集成测试。真正的单元测试会让您隔离您尝试测试的特定部分。

相关问题