[英]How to unit test express-http-proxy
I'm running a proxy service that adds a header to a request and forwards it to another API using express-http-proxy :我正在运行一个代理服务,该服务将 header 添加到请求中,并使用express-http-proxy将其转发到另一个 API :
app.use(
proxy(proxyUrl, {
proxyReqOptDecorator(proxyReqOpts, srcReq) {
proxyReqOpts.headers.customHeader = 'custom header'
return proxyReqOpts
},
})
)
How to unit test such a service?如何对这样的服务进行单元测试?
This is how I would test a normal express server:这就是我测试普通快递服务器的方式:
describe('proxy service', function() {
let server
beforeAll(() => {
server = app
})
afterAll(() => {
server.close()
})
describe('successful execution', () => {
test('responds to /', done => {
request(server)
.get('/')
.expect(200, done)
})
})
})
I want to validate what would be sent the external API without making the actual request.我想在不发出实际请求的情况下验证将发送到外部 API 的内容。
I have the same problem, my solution for now (until I find better one) is like this.我有同样的问题,我现在的解决方案(直到我找到更好的解决方案)是这样的。 (Using Jest)
(使用笑话)
First split the code on single responsability functions.首先将代码拆分为单一职责功能。 You should get something like this.
你应该得到这样的东西。
const injectHeaders = (req) => { // This is a pure function easy to UT
...
const headerA = ...
return (opts) => { // This is a pure function easy to UT
opts.headers[HEADERS.A] = headerA;
return opts;
};
};
Then your proxy code should look like this more or less那么你的代理代码应该或多或少像这样
app.use(
proxy(proxyUrl, {
proxyReqOptDecorator: injectHeaders,
})
)
And finale you can test it like this:最后你可以像这样测试它:
const expressProxy = require('express-http-proxy');
jest.mock('express-http-proxy')
test('proxy called with correct params', () => {
...execute app.use code ...
expect(expressProxy).toHaveBeenCalledWith(proxyUrl, {
proxyReqOptDecorator: injectHeaders,
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.