[英]Nock not intercepting http requests
I am currently using node-fetch
and nock
for an express server that sits on top of an angular project. 我目前正在将
node-fetch
和nock
用于位于角度项目顶部的Express服务器。
I have the following middleware that is making a call to an api: 我有以下中间件正在调用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)
}
}
and my test is as follows: 我的测试如下:
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();
})
})
})
However, nock is not mocking the data
response from the middleware function. 但是,nock并未模拟来自中间件功能的
data
响应。 Instead, I'd have to use scope
to access its parameters. 相反,我必须使用
scope
来访问其参数。
The middleware function acts as if nock never mocked its response. 中间件功能就像nock从未嘲笑它的响应一样。 Why is this occurring?
为什么会这样呢? Am I missing a configuration?
我是否缺少配置?
I am serving my tests using karma runner. 我正在使用业力赛跑者进行测试。
Nock works by overriding Node's http.request function.
Nock通过重写Node的http.request函数来工作。 Also, it overrides http.ClientRequest too to cover for modules that use it directly.
同样,它也覆盖http.ClientRequest,以覆盖直接使用它的模块。
Unfortunately it appears fetch
does not make use of the http.request
or http.ClientRequest
meaning the requests are never intercepted by nock
. 不幸的是,
fetch
似乎没有使用http.request
或http.ClientRequest
这意味着请求永远不会被nock
拦截。
A better approach may be to mock fetch
with a library such as fetch-mock
. 更好的方法可能是使用诸如
fetch-mock
类的库来模拟fetch
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.