我正在运行一个代理服务,该服务向请求添加 header 并使用 express-http-proxy 将其转发到另一个 API :
app.use(
proxy(proxyUrl, {
proxyReqOptDecorator(proxyReqOpts, srcReq) {
proxyReqOpts.headers.customHeader = 'custom header'
return proxyReqOpts
},
})
)
如何对这样的服务进行单元测试?
这是我测试普通 express 服务器的方式:
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)
})
})
})
我想在不发出实际请求的情况下验证将向外部 API 发送的内容。
最佳答案
我有同样的问题,我现在的解决方案(直到我找到更好的)是这样的。 (使用 Jest)
首先将代码拆分为单一职责功能。你应该得到这样的东西。
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;
};
};
那么你的代理代码应该差不多是这样的
app.use(
proxy(proxyUrl, {
proxyReqOptDecorator: injectHeaders,
})
)
最后你可以这样测试它:
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,
})
})
https://stackoverflow.com/questions/58952568/
相关文章:
ksqldb - KSQL 每组选择对应于具有最少时间戳的一行
sql-server - [Microsoft][SQL Server 的 ODBC 驱动程序 17
node.js - Npm 包安装在 nvm 的错误 Node 版本文件夹中
python - 为什么 pyautogui 热键不能一直在 mac 上工作?
angular - ng5- slider : Dragging pointers not movi
visual-studio-2019 - InvalidProjectFileException :
php - {YOURLS} 将 "shortening"接口(interface)设为私有(pri