目前,我正在使用node-fetch和nock作为一个快速服务器,该服务器位于一个角度项目的顶部。
下面是调用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从来没有模拟过它的响应一样。为什么会发生这种情况?,我是不是错过了配置?
我正在使用业力跑者为我的测试服务。
发布于 2019-05-27 14:37:42
Nock通过重写Node的http.request函数来工作。此外,它也覆盖http.ClientRequest,以覆盖直接使用它的模块。
不幸的是,fetch似乎没有使用http.request或http.ClientRequest,这意味着请求永远不会被nock拦截。
更好的方法可能是使用库(如fetch )来模拟fetch-mock。
https://stackoverflow.com/questions/54797719
复制相似问题