Javascript Nock不拦截http请求
我目前正在使用Javascript Nock不拦截http请求,javascript,node.js,unit-testing,testing,karma-jasmine,Javascript,Node.js,Unit Testing,Testing,Karma Jasmine,我目前正在使用node fetch和nock作为位于angular项目顶部的express服务器 我有以下中间件正在调用api: export const middleware = async(response: any) => { try { const result = await fetch(url).then(res => res.json()) return response.status(200).json(result);
node fetch
和nock
作为位于angular项目顶部的express服务器
我有以下中间件正在调用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并没有模拟来自中间件函数的数据
响应。相反,我必须使用scope
来访问它的参数
中间件功能的作用就好像nock从未模仿过它的响应一样。为什么会发生这种情况?我是否缺少配置
我正在使用karma runner进行测试
Nock通过覆盖节点的http.request函数来工作。此外,它还覆盖了http.ClientRequest,以覆盖直接使用它的模块
fetch
似乎没有使用http.request
或http.ClientRequest
,这意味着请求永远不会被nock
拦截
更好的方法可能是使用库(例如)模拟获取