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

标签 javascript json node.js superagent frisby.js

我想测试 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/

相关文章:

json - 在 golang 中持久化嵌套结构

javascript - 如何在 npm 项目中找到 node-gyp 依赖项(..或任何依赖项)

javascript - 拦截器未正确发送 header

javascript - 使用 Jquery 克隆 Select2

javascript - 数组映射和减少显示未定义的值

javascript - 如何找到两个或多个节点的最近共同祖先?

javascript - 在 Rails i18n 中插入 javascript var

javascript - 使用 list.js 排序/搜索时列表项消失

python - 将数据帧切成间隔以进行统计分析 | Python

node.js - HTTPS 还是 JWT 进行身份验证?