在帖子中断言整个回应主体

问题描述 投票:2回答:2

我最近开始从事春季启动项目。我正在寻找一种方法来断言我的API的整个响应。这样做的目的是减少API的测试时间。

找到了下面提到的一些解决方案,但没有任何帮助我解决这个问题。

pm.test("Body matches string", function () {
    pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});


pm.test("Body is correct", function () {
    pm.response.to.have.body("response_body_string");
});

当我把整个响应体作为参数时,我得到以下错误。

  1. 未封闭的字符串

2. enter image description here

3. enter image description here

json postman web-api-testing
2个回答
1
投票

如果你想使用相同类型的引号你在其中定义了字符串,你必须转义它们:

  • 'string with "quotes"'
  • "string with 'quotes'"
  • 'string with \'quotes\''
  • "string with \"quotes\""

您可能希望将json放在单引号中,因为json本身不允许这样做。


0
投票

您可以尝试将响应设置为变量,然后断言?

var jsonData = pm.response.json()

pm.environment.set('responseData', JSON.stringify(jsonData))

从这里你可以得到数据JSON.parse(pm.enviroment.get('responseData')),然后在任何测试中使用它来断言所有的值。

pm.test("Body is correct", () => {
    var jsonData = pm.response.json()
    pm.expect(jsonData).to.deep.equal(JSON.parse(pm.environment.get('responseData')))
})

我的理由是你试图断言JSON,但是做一个纯文本字符串。

或者你可以像这样单独断言值:

pm.test("Body is correct", () => {
    var jsonData = pm.response.json()
    pm.expect(jsonData[0].employeeName).to.equal("tushar")
    pm.expect(jsonData[0].phNum).to.equal(10101010)
})

根据JSON结构,您可能不需要访问数据数组,并且可以删除[0]

© www.soinside.com 2019 - 2024. All rights reserved.