2

I'm working on a Node.js/express application in typescript that includes a proxy route that has some custom business logic to determine the proxy 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")
                },
             }
        });
    }            
}

I can use mock-express-request to create Request/Response object, but I can't figure out how to plug it into the proxy.

Is there a way to inject a mock that intercepts the http client sending the proxy request? Ideally, somehow I could plug this function into 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;
}

Tried hooking into the proxy.onProxyReq and calling proxyReq.abort() and than trying to write directly to the Response, but that doesn't prevent a live request from going out.

Is there another way to hook into the http stack and mock out the network io?

1 Answer 1

2

You could consider using something like:

https://github.com/nock/nock

Instead of attempting to inject a mock, you can intercept the outgoing http requests and serve them with a mock server.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.