node.js - 试图使用 supertest 来检查响应的主体 - 得到一个错误

标签 node.js express 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)

这是超测中的错误,还是我的测试格式不正确?谢谢

最佳答案

或者,这也应该有效:

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);
});

现在您可以想象您正在为 /orgs/:orgId 测试 GET,并且您可以重复使用相同的验证。

关于node.js - 试图使用 supertest 来检查响应的主体 - 得到一个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339316/

相关文章:

javascript - UTF8解码汉字

node.js - Base64string 上的 Nodejs 有效负载太大(Http 413)

node.js - 使用 express、node.js 构建的 restful api 的单元测试日志记录(使用 mocha、supertest 和 chai)

node.js - Express.js 应用程序的单元测试与集成测试

javascript - 使用 supertest 测试 koa 路由时,内容类型 header 始终相同

Mongoose 查询时Javascript变量范围

node.js - 比较服务器上的客户端时间

javascript - 发送后无法设置 header 。调用 create(data,cb) 时

node.js - Sails ORM(Waterline)回调中的自定义错误

android - 安装 ionic cordova 时出错