javascript - Nock 不拦截 http 请求
问题描述
我目前正在使用node-fetch
andnock
用于位于 Angular 项目之上的快速服务器。
我有以下正在调用 api 的中间件:
export const middleware = async(response: any) => {
try {
const result = await fetch(url).then(res => res.json())
return response.status(200).json(result);
} catch(err) {
logger.error({eventId: 'get-content', err});
return response.status(500)
}
}
我的测试如下:
describe('API service', () => {
let response, scope;
beforeEach(() => {
response = {
status(s) { this.statusCode = s; return this; },
json(result) { this.res = result; return this; },
};
})
afterEach(() => {
nock.restore();
})
it('should return a 200 response from successful call api', (done) => {
scope = nock(url)
.get(/.*/)
.reply(200, {data: 'content'})
middleware(response).then(data => {
expect(response.status).toEqual(200);
expect(response.data).toEqual('content');
scope.isDone();
done();
})
})
})
然而, nock 并没有模拟data
来自中间件函数的响应。相反,我必须使用scope
它来访问它的参数。
中间件函数的行为就好像 nock 从未嘲笑过它的响应。为什么会出现这种情况?我缺少配置吗?
我正在使用 karma runner 进行测试。
解决方案
Nock 通过覆盖 Node 的 http.request 函数来工作。此外,它也覆盖了 http.ClientRequest 以覆盖直接使用它的模块。
不幸的是,它似乎fetch
没有使用http.request
或http.ClientRequest
意味着请求永远不会被nock
.
更好的方法可能是fetch
使用诸如fetch-mock
.
推荐阅读
- wso2 - 使用迁移工具将 API 从 API Manager 开发环境迁移到测试环境
- javascript - 通过网络浏览器加载数组列表
- python - Tkinter 代码适用于 Windows 但不适用于 Mac
- apache-kafka - 具有相同密钥但来自不同 Kafka 生产者的消息会转到不同的分区吗?
- python - 无法在交互式 IPython 之外启动本地 dask 客户端
- ios - 以编程方式创建的动画 NSLayoutConstraint
- c# - 是否有更通用的解决方案?
- python - 如何根据两个不同列的值在一列中填充 NaN
- wordpress - Httpd 只允许访问直接在 /var/www/html 文件夹中创建的文件
- android - 将 Java 位图打包到 ByteBuffer 中 - 字节顺序与像素格式和字节序不匹配(ARM)