【问题标题】:How to set up code coverage and unit tests for express functions?如何为 express 函数设置代码覆盖率和单元测试?
【发布时间】:2015-06-03 19:08:52
【问题描述】:

我的路线定义如下

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'

【问题讨论】:

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


【解决方案1】:

有多种代码覆盖工具,其中许多都集成在不同的构建系统中(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 并收工,但对我来说,这将使它成为一个集成测试。真正的单元测试会让您隔离您正在尝试测试的特定部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2023-04-07
    • 1970-01-01
    • 2010-10-14
    • 2013-04-16
    相关资源
    最近更新 更多