Sam*_*duc 18 testing mocha.js node.js
我开始向Node.js服务器应用程序添加测试,因为我们正在慢慢部署到生产环境中.我有一个API,有许多可能的测试请求.
我的问题是:你如何构建你的测试,所以它不会成为你很快迷路的大文件?
我为一个 API路由编写了测试(我有许多其他API路由要测试),这就是它的外观(在Sublime文件概述中):

而这项测试甚至还没有涵盖所有案例.
我使用mocha,连同should和expect进行验证,并superagent为API调用.你将如何构建这些测试,以便它不会在一个可怕的大文件中进化?
srq*_*inn 28
有很多方法可以将文件分解为更小,更易于管理的部分.他们中的大多数围绕着使用--recursive旗帜mocha.最后,它是个人选择的问题,对团队/个人有用.
在mocha没有--recursive标志的情况下运行并使用点表示法命名文件.然后,您可以通过HTTP方法进一步细分,如果您愿意,可以通过pass/fail进一步细分.例如,用户路由将具有文件名,route.user.get.pass.js并且位于test/文件夹的根目录中.该文件的代码如下所示:
describe('GET /users', function () {
describe('when the request is valid', function () {
it('should return 200 OK');
it('should have unicorns');
it('should have ponies too');
});
});
Run Code Online (Sandbox Code Playgroud)
然后另一个文件名测试route.resource.post.fail.js看起来像:
describe('POST /users', function () {
describe('when the request is invalid', function () {
it('should return 400 Bad Request');
...
});
});
Run Code Online (Sandbox Code Playgroud)
这使得在使用mochagrep功能时,grepping个人测试变得轻而易举
但是,与选项1类似,在这种情况下,您将--recursive在运行时使用该标志mocha并使用文件夹而不是嵌套文件名.
test/
routes/
users/
post.js
get.js
put.js
models/
User.js
Run Code Online (Sandbox Code Playgroud)
这种方法是前两种的组合,应该在没有--recursive标志的情况下运行.在test目录的根目录中,您可以将spec文件命名为以下routes.userSpec.js代码:
describe('/users', function () {
describe('GET', function () {
var tests = require('./users/get');
it('should return 200 OK', tests.200);
it('should have unicorns', tests.unicorns);
it('should have ponies too', tests.ponies);
});
describe('POST', function () {
var tests = require('./users/post');
it('should return 200 OK', tests.200);
it('should create unicorns', tests.unicorns);
it('should create ponies too', tests.ponies);
});
});
Run Code Online (Sandbox Code Playgroud)
然后你会在test/users文件夹中定义模块,如下所示:
test/
users/
get.js
post.js
routes.userSpec.js
Run Code Online (Sandbox Code Playgroud)
有时大文件是不可避免的,这就是所有优秀文本编辑器都具有代码折叠功能的原因.