【问题标题】:Mock a Node Js Proxy模拟 Node Js 代理
【发布时间】:2019-11-05 10:37:55
【问题描述】:

我正在使用 typescript 开发一个 Node.js/express 应用程序,其中包括一个代理路由,该路由具有一些自定义业务逻辑来确定代理 URL:

import proxy from "http-proxy-middleware";

const controller = diContainer.get<IController>(TYPES.Controller);
const app = express();
app.use("/customProxy", controller.handleProxy());

@injectable()
export class Controller implements IController {
   public handleProxy(): RequestHandler {
        return proxy(
            "**", // proxy all incoming routes
            {
                router: (req: Request) => {           
                   // custom logic to translate route
                   return customRouteBasedOnIncomingRequest;
                },
                onProxyRes: (proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse) => {
                    // custom logic to set outgoing response
                    res.setHeader("custom", "header")
                },
             }
        });
    }            
}

我可以使用mock-express-request 创建请求/响应对象,但我不知道如何将其插入proxy

有没有办法注入一个模拟来拦截发送代理请求的 http 客户端? 理想情况下,我可以以某种方式将此函数插入​​Controller

public mockedHttpServer(req: Request):Response
{
   const res = new MockExrpessResponse();

   if (req.url == "http://expected.url"){
      res.write("success");
      res.statuscode = 200;
   }
   else{
     res.statuscode = 404;
   }

   return res;
}

尝试挂接到proxy.onProxyReq 并调用proxyReq.abort(),而不是尝试直接写入Response,但这并不能阻止实时请求发出。

还有其他方法可以连接到 http 堆栈并模拟网络 io 吗?

【问题讨论】:

    标签: typescript express mocking http-proxy cucumberjs


    【解决方案1】:

    你可以考虑使用类似的东西:

    https://github.com/nock/nock

    您可以拦截传出的 http 请求并使用模拟服务器为它们提供服务,而不是尝试注入模拟。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 2021-12-21
      • 2017-10-15
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多