gpt4 book ai didi

javascript - 测试 API 如何使用 node.js 处理无效的 JSON 语法请求正文

转载 作者:IT老高 更新时间:2023-10-28 23:20:58 27 4
gpt4 key购买 nike

我想测试 REST API 如何处理具有无效 JSON 语法的正文的 POST 请求,例如缺少逗号。我正在使用 node.js 编写 API 测试。我正在使用 frisby但我也试过supertest .没运气。使用之前的工具,您将请求正文作为 JavaScript 对象传递,因此行不通。我还尝试将无效的 JSON 作为字符串传递,但没有任何运气,因为字符串也是有效的 JSON(下面的示例)。有什么想法吗?

frisby.create('Ensure response has right status')
.post('http://example.com/api/books', '{"invalid"}', {json: true})
.expectStatus(400)
.toss();

最佳答案

使用 supertest 和 mocha 包,您可以通过发布无效的 JSON 来测试端点,如下所示:

var request = require('supertest');

describe('Adding new book', function(){
it('with invalid json returns a 400', function(done){
request('http://example.com').post('/api/books')
.send('{"invalid"}')
.type('json')
.expect('Content-Type', /json/)
.expect(400)
.end(function(err, res) {
console.log(res.error);
done();
});
});
});

这里重要的一点是type(json)。这会将请求的 Content-Type 设置为 application/json。没有它,supertest/superagent 将默认以 application/x-www-form-urlencoded 形式发送字符串。此外,无效的 JSON 作为字符串而不是 JavaScript 对象提供。

关于javascript - 测试 API 如何使用 node.js 处理无效的 JSON 语法请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28286073/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com