在浏览器中进行RESTful API测试

RESTful API testing in a browser

本文关键字:RESTful API 测试 浏览器      更新时间:2023-09-26

我正在编写RESTful应用程序,以及文档。因为文档是作为网页编写的,所以我希望在文档中嵌入REST服务测试。

我使用Jasmine进行测试,并一直在寻找测试REST调用的一些简化。Frisby看起来像我需要的东西,但它在Node.js中运行,而不是浏览器。

你知道有什么类似于Frisby测试的库,但是在浏览器环境中吗?为了它的价值,我找到了SuperTest,它运行在便携式超级代理上,但我不知道它是否可以与Jasmine一起使用(它们与摩卡密切相关)。

UPDATE:不,supertest不(尚未)在浏览器中工作:(

最后,我编写了自己的一小组包装SuperAgent的辅助函数。现在测试代码(CoffeeScript和Jasmine)如下所示:

describe "A suite", ->
    resource = null
    it "and a spec", (done) ->
        expectResponse(request.get "/path/to/resource")
            .ok()
            .json()
            .andDo (response) -> resource = response.body
            .end(done)

和一个像这样的帮助类

class ExpectResponseWrapper
    constructor: (req) ->
        @req = req
        @expectations = []
    end: (done) ->
        @req.end (err, res) =>
            if (err)
                expect( -> throw err).not.toThrow()
            else
                for exp in @expectations
                    exp(res)
            done?()
    ok: ->
        @expectations.push (res) ->
            expect(res.statusType).toEqual(2)
        this
    json: ->
        @expectations.push (res) ->
            expect(res.type).toEqual('application/json')
        this
    andDo: (fn) ->
        @expectations.push fn
        this
    # ... and the list of other helper expectations goes on ...
expectResponse = (req) -> new ExpectResponseWrapper(req)