我目前正在使用 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 并没有模拟来自中间件函数的data
响应。相反,我必须使用 scope
来访问其参数。
中间件函数的行为就像 nock 从未 mock 过它的响应一样。为什么会发生这种情况?我是否缺少配置?
我正在使用 karma runner 提供测试。
最佳答案
Nock works by overriding Node's http.request function. Also, it overrides http.ClientRequest too to cover for modules that use it directly.
不幸的是,fetch
似乎没有使用 http.request
或 http.ClientRequest
,这意味着请求永远不会被 拦截>诺克
。
更好的方法可能是使用诸如 fetch-mock
之类的库来模拟 fetch
.
关于javascript - Nock 不拦截 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54797719/