是否可以使用“假"代码直接从代码中调用 Express Router?要求? [英] Is it possible to call Express Router directly from code with a "fake" request?

查看:19
本文介绍了是否可以使用“假"代码直接从代码中调用 Express Router?要求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题相切,我想知道是否有是一种无需通过 HTTP 即可触发 Express Router 的方式?

Tangential to this question, I would like to find out if there is a way of triggering the Express Router without actually going through HTTP?

推荐答案

Router有一个私有"方法,名为 handle,接受请求、响应和回调.您可以查看 Express 对其 Router<的测试/a>.一个例子是:

The Router has a "private" method named handle that accepts a request, a response, and a callback. You can take a look at the tests that Express has for its Router. One example is:

it('should support .use of other routers', function(done){
    var router = new Router();
    var another = new Router();

    another.get('/bar', function(req, res){
      res.end();
    });
    router.use('/foo', another);

    router.handle({ url: '/foo/bar', method: 'GET' }, { end: done });
  });

Express 团队使用 SuperTest路由器.据我了解,SuperTest 仍然使用网络,但它们会为您处理所有这些,因此它的行为就像测试都在内存中一样.SuperTest 似乎被广泛使用并且是一种可接受的测试路线的方法.

The Express team uses SuperTest to perform integration tests on the Router. It is my understanding that SuperTest still uses the network but they handle all of this for you so it behaves as if the tests were all in memory. SuperTest does seem to be widely used and an acceptable way to test your routes.

顺便说一句,您没有说明您要测试什么,但如果您的目标是测试某些路由,SuperTest 的替代方法可能是将您的路由中的逻辑提取到一个可以独立测试的单独模块中快递.

As an aside, you didn't say what you were attempting to test but if your goal is to test some routes, an alternative to SuperTest could be to extract the logic in your routes into a separate module that can be tested independent of Express.

改变:

routes
|
-- index.js

到:

routes
|
-- index.js
|
controllers
|
-- myCustomController.js

然后,测试可以简单地以 myCustomController.js 为目标并注入任何必要的依赖项.

The tests could then simply target myCustomController.js and inject any necessary dependencies.

这篇关于是否可以使用“假"代码直接从代码中调用 Express Router?要求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆