testingAPI如何使用node.js处理无效的JSON语法请求主体

我想testing一个REST API如何处理一个具有无效JSON语法的主体的POST请求,例如一个缺less的逗号。 我正在使用node.js来编写APItesting。 我正在使用弗里斯比,但我也尝试超级 。 没有运气。 使用以前的工具,您将请求主体作为JavaScript对象传递,所以不行。 我也试图通过无效的JSON作为一个string没有任何运气,因为一个string也是有效的JSON(下面的例子)。 有任何想法吗?

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

我从来没有使用弗里斯比或superagent,但我觉得这里有两个问题:

1.使用POST方法将无效的JSON从客户端传递到服务器。

这是不可能的,因为它在客户端本身很快就会被拒绝,并且在向服务器发送POST请求之前你会得到错误。 (因为在使用http时只有string,客户端本身会尝试对JSON进行string化处理,从而导致无效的JSON)

2.传递一个无效的JSON就像一个string

例如:使用JQuery POST这样的string

  $.post("demo_test_post.asp", { name: 'pqr:{"abc":"abc",}' // see there is a comma at the end making JSON invalid }, function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); 

这将有效地将无效的JSON(本例中的名称)作为srting传递给服务器。 但是,这将需要您使用JSON.parse()parsingstring为JSON,然后才能使用它。 而当你尝试你得到这个:

SyntaxError: 意外的标记p在Object.parse (本地)在Object.app.get.res.send.data [作为句柄](/home/ubuntu/workspace/TapToBook.js:35:19)在next_layer(/ home / ubuntu / workspace / node_modules / express / lib / router / route.js:103:13)at Route.dispatch(/home/ubuntu/workspace/node_modules/express/lib/router/route.js:107:5)at proto (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:195:24)在Function.proto.process_params(/ home / ubuntu / workspace / node_modules / express / lib / router / (/ home / ubuntu / workspace / index.js:251:12)在下一个(/home/ubuntu/workspace/node_modules/express/lib/router/index.js:189:19)在Layer.staticMiddleware [ node_modules / express / node_modules / serve-static / index.js:55:61)在trim_prefix(/home/ubuntu/workspace/node_modules/express/lib/router/index.js:226:17)at proto.handle.c (/home/ubuntu/workspace/node_modules/express/lib/router/index.js:198:9)

因此,无论您将Rest用于哪个软件包,都可以将无效的JSON作为string传递,但不能使用它。

使用supertest和mocha包,您可以通过发布无效的JSON来testing端点:

 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) 。 这将把请求的内容types设置为application / json。 超出它,supertest / superagent将默认发送string作为application / x-www-form-urlencoded。 此外,无效的JSON以stringforms提供,而不是JavaScript对象。

我假设你的testing想要validation服务器正在处理无效的JSON(并不会崩溃)。 希望能够回复400个错误的请求。

由于http中的POST只是一个string,所以testing的一个选项是使用一个需要提供JSON对象的API。

如果你使用原始节点http,那么你可以发送任何你想要的无效string:

如何在node.js中创buildHTTP POST请求?

还有stream行的请求库。

https://github.com/request/request

例如,对于图书馆来说,您的testing可以从文件中提取无效内容并进行发布或放置。 从他们的文档:

 fs.createReadStream('file.json').pipe(request.put('http://example.com/obj.json'))