有很多方法可以将文件分解成更小、更易于管理的部分。他们中的大多数都围绕在mocha 中使用--recursive 标志。最后,这取决于个人选择以及对团队/个人有效的方法。
选项 1:通过点表示法命名空间
运行不带--recursive 标志的mocha 并使用点符号命名您的文件。然后,您可以通过 HTTP 方法进一步分解它,如果您愿意,可以通过通过/失败进一步分解。例如,用户路由的文件名类似于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');
});
});
然后另一个文件名为 route.resource.post.fail.js 的测试看起来像:
describe('POST /users', function () {
describe('when the request is invalid', function () {
it('should return 400 Bad Request');
...
});
});
当使用mocha 的 grep 功能时,这使得 grepping 个人测试变得轻而易举
选项 2:通过文件夹命名空间
但是,与选项 1 类似,在这种情况下,您将在运行 mocha 时使用 --recursive 标志并使用文件夹而不是嵌套文件名。
test/
routes/
users/
post.js
get.js
put.js
models/
User.js
选项 3:使用模块分隔
这种方法是前两种方法的组合,应该在没有--recursive 标志的情况下运行。在test 目录的根目录中,您可以将规范文件命名为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);
});
});
然后您将在 test/users 文件夹中定义模块,如下所示:
test/
users/
get.js
post.js
routes.userSpec.js
选项 4:代码折叠
有时大文件是不可避免的,这就是为什么所有优秀的文本编辑器都具有代码折叠功能的原因。