egg 已经集成了urllib,app.curl、ctx.curl。内置httpclient使用,同时可以使用app.mockHttpclient 进行 test拦截测试。
但是在midway中由于使用了inject而无法使用curl中的 上下文this.httpclient。
所以可以使用注入方式:
方式一 app.curl:
// app.ts for app.curl
/**
* 注册全局对象
*/
app.applicationContext.registerObject('curl', (url: string, option: RequestOptions) => {
return app.curl(url, option);
});
方式二 ctx.curl:
// 自定义ts文件
export const curlFactory = (context: any) => {
return (url: string, option: RequestOptions) => {
return context.ctx.curl(url, option);
};
};
providerWrapper([
{
id: 'curl',
provider: curlFactory
}
]);
使用方式:
@inject()
curl: <T = any>(url: string, option: RequestOptions) => Promise<HttpClientResponse<T>>;
const url = 'http://www.baidu.com';
const result = await this.curl(url, {
dataType: 'json'
});
test:
重点代码 app.mockHttpclient url对应上文中的调用地址
it('get /code2session/{code}', async () => {
app.mockHttpclient('http://www.baidu.com', {
data: {
openid: 'test0001',
sessionKey: 'test0001',
unionid: 'testunit'
}
});
const result = await app
.httpRequest()
.get('/mini-app/code2session/123456')
.set('servertoken', token);
assert(result.status === 200);
assert(result.body && code2SessionOut.validate(result.body).error === null);
console.log(result.body);
});
网友评论