试图使用supertest来检查响应的主体 – 得到一个错误
我正在尝试使用supertest进行一些testing。 这是我想要testing的代码片段:
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(); }); });
尝试testingres体时出现错误:
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)
这是超级错误,还是我格式化我的testing不正确? 谢谢
另外,这也应该工作:
res.body.should.have.property("name", "new_org");
此外,只是一个说明,但在逻辑上,我认为这是有道理的把它放在另一个电话,而不是在最后的callback。 这个函数也可以重用,所以我倾向于把它放在可重用的地方:
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); });
现在你可以想象你正在为/orgs/:orgId
testing一个GET
,你可以重新使用相同的validation。
这可以被重写如下:
res.body.name.should.equal("new_org");
这将解决这个错误。
如果你的res.body是一个数组,你需要提供对象的索引,所以res.body[res.body.length -1].name.should.equal("new_org")
– 如果你的属性是最后一个数组并没有sorting