test2doc.js - 从测试用例自动生成 API 文档
发布于 7 年前 作者 stackia 3450 次浏览 来自 分享

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

// For Koa, you should exports app.listen() or app.callback() in your app entry
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

1 回复

谢谢分享,正好需要一个这样的东西

回到顶部