简体   繁体   English

在单元测试期间如何模拟代理?

[英]How to simulate proxy during unit testing?

I have a Node.js library that makes https.request ( https://nodejs.org/api/https.html ) calls to external sources. 我有一个Node.js库,可以对外部源进行https.requesthttps://nodejs.org/api/https.html )调用。

In some cases, the user of the library may be behind a proxy. 在某些情况下,库的用户可能位于代理之后。 Due to configuration (or misconfiguration?) of the proxy, users behind the proxy may experience issues with SSL certificates. 由于代理的配置(或配置错误?),代理后面的用户可能会遇到SSL证书问题。 In this case, in order to make https requests in Node, you need to set the https.request option: rejectUnauthorized to be false . 在这种情况下,为了在Node中发出https请求,您需要设置https.request选项: rejectUnauthorizedfalse (on a related note, these proxies typically require npm --strict-ssl=false as well) (有关说明,这些代理通常也需要npm --strict-ssl=false

How can I setup a test that simulates being behind a proxy that rejects signed certificates so that I can ensure that my library will work properly for those behind proxies such as these? 我该如何设置一个测试来模拟位于被拒绝签名证书的代理后面的测试,以便可以确保我的库对于像这些代理这样的代理正确运行?

I'm using mocha and/or chai as the testing library and nock to simulate external sources that are being called. 我使用mocha和/或chai作为测试库,并使用nock模拟被调用的外部源。

I would wrap the request in a function in a module so that it can be mocked to have the behaviour that you want. 我会将请求包装在模块中的函数中,以便可以模拟它以具有所需的行为。

I believe this answer is a good example. 我相信这个答案是一个很好的例子。

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

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