我已经解决这个问题有一段时间了,但我无法让现有的解决方案为我工作。
我有一个用 Express.js 编写的 Node.js API。我一直在使用 Mocha、Chai 和 Supertest 为 API 编写测试。这些测试主要是集成测试。
一项测试可能如下所示:
it('should fail to register a new user without the proper information', function(done) {
api.post('/user')
.send({})
.expect(400)
.expect('Content-Type', /json/)
.end(function(err, res) {
should.exist(res.body);
should.exist(res.body.error);
should.not.exist(err);
res.body.error.should.contain('Username');
res.body.error.should.contain('password');
done();
});
});
实际测试效果很好,但现在我需要能够查看这些测试的代码覆盖率。我必须知道我没有充分测试什么。我尝试过使用 Mocha 的测试覆盖率:
mocha -R html-cov --coverage > coverage.html
and伊斯坦布尔的:
istanbul cover _mocha -- -R spec --timeout 5000
两者都面临同样的问题:
您看,这是一个示例路线(用户注册)。我的测试肯定涵盖了它,但由于它们不直接调用此方法,因此覆盖工具假设它从未被调用。这就是问题所在 - 代码覆盖工具没有捕获最终执行的代码。
我尝试了另一种解决方案 -伊斯坦布尔中间件 https://github.com/gotwarlost/istanbul-middleware,实际上似乎更好地捕获了信息(尽管它很hacky)。然而,这里的相同路线看起来像:
这显然也是不可取的。当然其他应用程序也遇到过这个问题,他们是如何解决的呢?
Note:我还安装了 jscoverage 以使这一切正常工作。
我看过的资料来源:
https://brianstoner.com/blog/testing-in-nodejs-with-mocha/ https://brianstoner.com/blog/testing-in-nodejs-with-mocha/
http://boycook.wordpress.com/2013/03/29/automated-javascript-testing-with-mocha-and-js-coverage-for-nodejs/ http://boycook.wordpress.com/2013/03/29/automated-javascript-testing-with-mocha-and-js-coverage-for-nodejs/
Mocha 的代码覆盖率 https://stackoverflow.com/questions/16633246/code-coverage-with-mocha