简体   繁体   English

使用supertest和Express JS测试下一个(错误)

[英]Testing for next(err) with supertest and Express JS

In a route or middleware in Express, you can skip the remaining call chain by invoking next(err) where err is any object. 在Express中的路由或中间件中,您可以通过调用next(err)跳过剩余的调用链,其中err是任何对象。 This is pretty straightforward from the docs. 从文档中可以很简单。

When testing with SuperTest, this workflow does not seem to be supported. 使用SuperTest进行测试时,似乎不支持此工作流程。 The only error result from the middleware to supertest, is that the text on the response is set to [object Object] . 中间件到supertest的唯一错误结果是响应上的文本设置为[object Object]

For example: 例如:

const request = require('supertest');
const app = express();
app.use( (req, res, next) => next({ error: "ErrorCode" }) );
request(app).get('/')
  .expect(500)
  .end(function(err, res) {
    // err == undefined
    // res.text === '[object Object]'
  });

Is there a way with supertest to validate the object passed to the next() callback? 有没有办法用supertest来验证传递给next()回调的对象?

I obviously could use sinon+chai or jasmine to straight unit test the code, but I'm curious if this is possible with just supertest, and maybe even a supporting bespoke middleware after the testable unit. 我显然可以使用sinon + chai或jasmine直接对代码进行单元测试,但我很好奇这是否可能只是超级,甚至可以在可测试单元之后支持定制的中间件。

Supertest works at the HTTP response level, so it can only check the status, headers, body of the response itself based on the HTTP message. Supertest在HTTP响应级别工作,因此它只能根据HTTP消息检查响应本身的状态,标题和正文。 It cannot check javascript-level details about the code inside the express app (supertest can actually check arbitrary HTTP servers written in any language, it just has some convenience code for express). 它无法检查有关Express应用程序内部代码的javascript级详细信息(supertest实际上可以检查用任何语言编写的任意HTTP服务器,它只是有一些便捷代码用于表达)。

Thus first I'd write an error handler middleware that translates your error objects (which really should be Error instances instead of plain objects), sets the proper status code, content type, body, etc. Then make your supertest associations for those attributes. 因此,首先我要编写一个错误处理程序中间件来转换您的错误对象(实际上应该是Error实例而不是普通对象),设置正确的状态代码,内容类型,正文等。然后为这些属性建立超级联想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM