V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
jsq2627
V2EX  ›  分享创造

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

  •  
  •   jsq2627 ·
    stackia · 2017-02-22 18:35:46 +08:00 · 2041 次点击
    这是一个创建于 2619 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 核心功能完善好再考虑发展周边生态。

    1 条回复    2017-02-23 09:39:31 +08:00
    Patrick95
        1
    Patrick95  
       2017-02-23 09:39:31 +08:00
    很赞!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1000 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 20:15 · PVG 04:15 · LAX 13:15 · JFK 16:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.