如何检查POST请求的纯文本响应?

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

我正在尝试使用frisby.js为端点指定API测试,该端点返回对有效POST请求的纯文本响应。但是我在使用frysby.js接受非JSON响应文档时遇到了问题。每当响应返回非JSON内容时,由于TypeError而抛出'Unexpected token b in JSON at position 0'

作为一个例子,我发送一个带有下面显示的JSON文档的HTTP POST请求,预计会返回一个带有字符串bar的明文文档的响应。

{
    "foo":{
        "name":"bar"
    }
}

这是我为验证响应而编写的单元测试:

it('should create a foo resource', function () {
  return frisby.post('http://localhost:8080/', 
      {
        "foo":{
          "name":"bar"
        }
      })
    .expect('status',201);
});

不幸的是,当我运行测试时,frisby.js会抛出以下错误:

FAIL./test.js✕应该创建一个foo资源(17ms)

●应该创建一个foo资源

TypeError:无效的json响应正文:http://localhost:8080/上的'bar'原因:'位于0的JSON中的意外标记b'

有谁知道是否可以配置每个测试以期望除JSON之外的某些数据格式?

node.js web-api-testing frisby.js
1个回答
0
投票

如果你得到JSON +的东西然后以两种格式打破jsonTypes,比如JSON对象和JSON对象中的数组。然后把期望条件放在他们身上。

这可能会帮助您:

const frisby = require('frisby');
const Joi = frisby.Joi;

frisby.globalSetup({
    headers : {
        "Accept": "application/json", 
        "content-type" : "application/json",
    }
});

it("should create a foo resource", function () {
    frisby.post("http://localhost:8080/")
        .expect("status", 200)
        .expect("header", "content-type", "application/json; charset=utf-8")
        .expect("jsonTypes", "data.foo", {
            "name": Joi.string()
        })
        .then(function(res) { // res = FrisbyResponse object
            var body = res.body;
            body = JSON.parse(body);

            expect(body.data.foo.name).toBeDefined();
        })
});
© www.soinside.com 2019 - 2024. All rights reserved.