试图使用supertest检查响应的主体 - 得到错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了试图使用supertest检查响应的主体 - 得到错误相关的知识,希望对你有一定的参考价值。
我正在尝试使用supertest进行一些测试。以下是我要测试的代码段:
it("should create a new org with valid privileges and input with status 201", function(done) {
request(app)
.post("/orgs")
.send({ name: "new_org", owner: "oldschool@aol.com", timezone: "America/New_York", currency: "USD"})
.expect(201)
.end(function(err, res) {
res.body.should.include("new_org");
done();
});
});
我在尝试测试res主体时遇到错误:
TypeError: Object #<Object> has no method 'indexOf'
at Object.Assertion.include (../api/node_modules/should/lib/should.js:508:21)
at request.post.send.name (../api/test/orgs/routes.js:24:27)
at Test.assert (../api/node_modules/supertest/lib/test.js:195:3)
at Test.end (../api/node_modules/supertest/lib/test.js:124:10)
at Test.Request.callback (../api/node_modules/supertest/node_modules/superagent/lib/node/index.js:575:3)
at Test.<anonymous> (../api/node_modules/supertest/node_modules/superagent/lib/node/index.js:133:10)
at Test.EventEmitter.emit (events.js:96:17)
at IncomingMessage.Request.end (../api/node_modules/supertest/node_modules/superagent/lib/node/index.js:703:12)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socketOnData [as ondata] (http.js:1367:20)
at TCP.onread (net.js:403:27)
这是supertest中的错误,还是我错误地格式化了我的测试?谢谢
答案
或者,这也应该工作:
res.body.should.have.property("name", "new_org");
另外,只是一个注释,但从逻辑上来说,我认为将其放入另一个调用expects
而不是最终回调中是有意义的。此函数也可以重复使用,因此我倾向于在可能的情况下将其放在可重用的位置:
var isValidOrg = function(res) {
res.body.should.have.property("name", "new_org");
};
it("should create a new org with valid privileges and input with status 201", function(done) {
request(app)
.post("/orgs")
.send({ name: "new_org", owner: "oldschool@aol.com", timezone: "America/New_York", currency: "USD"})
.expect(201)
.expect(isValidOrg)
.end(done);
});
现在你可以想象你正在为GET
测试/orgs/:orgId
,你可以重新使用相同的验证。
另一答案
这可以改写如下:
res.body.name.should.equal("new_org");
这将解决错误。
另一答案
如果你的res.body是一个数组,你需要提供对象的索引,所以res.body[res.body.length -1].name.should.equal("new_org")
- 如果你的属性是数组中的最后一个而没有订购
另一答案
要测试响应体,您可以在expect
中包含预期的响应,
const { describe, it } = require('mocha');
const supertest = require('supertest');
describe('Validate API calls', () => {
it('create session post request should fail for invalid credentials', (done) => {
const data = { user_name: 'incorrect_username', password: 'INVALID' };
supertest(app).post('/api/session')
.send(data)
.expect('Content-Type', /json/)
.expect({ name: 'AuthenticationError', message: 'Unauthorized' })
.expect(401, done);
});
});
来源:https://willi.am/blog/2014/07/28/test-your-api-with-supertest/
以上是关于试图使用supertest检查响应的主体 - 得到错误的主要内容,如果未能解决你的问题,请参考以下文章
Retrofit-非空主体上的onFailure,空主体上的onResponse
在 Typescript 中使用 Jest + Supertest 进行模拟
尝试使用 node.js supertest 发布 multipart/form-data