test2doc.js - 从测试用例自动生成 API 文档 [node.js]

2017-02-22 18:35:46 +08:00
 jsq2627

API 文档总是和代码不能同步?

手动编写每个请求 body 和响应 body 十分繁琐?

API 文档无法进行版本管理?

也许你该试试从测试用例自动生成 API 文档~

test2doc.js 为这个目标而生,帮助你轻松把 API 文档生成工作集成到你的测试流程中。

test2doc.js 设计为不面向特定测试框架、断言框架、请求框架,你可以灵活地集成到自己的项目里面。

如果你恰好使用 mocha / should / supertest 为自己地应用编写过测试的话,下面这段代码你应该有几分熟悉:

const doc = require('test2doc')
const request = require('supertest') // We use supertest as the HTTP request library
require('should') // and use should as the assertion library
const app = require('./my-express-app.js')

after(function () {
  doc.emit('api-documentation.apib')
})

doc.group('Products').is(doc => {
  describe('#Products', function () {
    doc.action('Get all products').is(doc => {
      it('should get all products', function () {
        // Write specs towards your API endpoint as you would normally do
        // Just decorate with some utility methods
        return request(app)
          .get(doc.get('/products'))
          .query(doc.query({
            minPrice: doc.val(10, 'Only products of which price >= this value should be returned')
          }))
          .expect(200)
          .then(res => {
            body = doc.resBody(res.body)
            body.desc('List of all products')
              .should.not.be.empty()
            body[0].should.have.properties('id', 'name', 'price')
            body[0].price.desc('Price of this product').should.be.a.Number
          })
      })
    })
  })
})

只需把 url / request body / response body 等想要进入文档的内容交给 test2doc.js 捕获即可。

test2doc.js 不规定生成文档的格式,你可以实现自己的 generator ,利用 test2doc.js 捕获的信息生成自己想要的文档格式。 test2doc.js 目前内置实现了一个 API Blueprint 的生成器。

项目地址: https://github.com/stackia/test2doc.js

当前还处于 0.0.x 版本,依旧有诸多不完善之处,文档也比较简陋。但是这种工具类程序还是需要在使用中发现缺陷的,希望敢于尝鲜的朋友可以试试它~~


目前公司项目组已经尝试使用这种方式生成文档,确实非常方便。

上面这种文档标注形式目前看起来依旧略有繁琐,我打算再实现一个 supertest 的扩展来简化语法。当然这是后话了,先把 test2doc.js 核心功能完善好再考虑发展周边生态。

2043 次点击
所在节点    分享创造
1 条回复
Patrick95
2017-02-23 09:39:31 +08:00
很赞!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/342401

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX