ale*_*ris 10 javascript json node.js superagent frisby.js
我想测试REST API如何处理具有无效JSON语法的主体的POST请求,例如缺少逗号.我正在使用node.js编写API测试.我正在使用frisby,但我也尝试了超级.没运气.使用以前的工具,您将请求主体作为JavaScript对象传递,因此不行.我还尝试将无效的JSON作为字符串传递而没有任何运气,因为字符串也是有效的JSON(下面的示例).有任何想法吗?
frisby.create('Ensure response has right status')
.post('http://example.com/api/books', '{"invalid"}', {json: true})
.expectStatus(400)
.toss();
Run Code Online (Sandbox Code Playgroud)
使用 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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
这里的重要一点是type(json)。这会将请求的 Content-Type 设置为 application/json。没有它,supertest/superagent 将默认将字符串作为 application/x-www-form-urlencoded 发送。此外,无效的 JSON 以字符串形式提供,而不是作为 JavaScript 对象提供。
| 归档时间: |
|
| 查看次数: |
5786 次 |
| 最近记录: |