Philip Pittle
Philip Pittle

Reputation: 12295

Mock a Node Js Proxy

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?

Upvotes: 2

Views: 1886

Answers (1)

silijon
silijon

Reputation: 942

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.

Upvotes: 2

Related Questions