美文网首页
midway curl、test 集成方案

midway curl、test 集成方案

作者: 吴占超 | 来源:发表于2019-07-24 14:00 被阅读0次

    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);
      });
    

    相关文章

      网友评论

          本文标题:midway curl、test 集成方案

          本文链接:https://www.haomeiwen.com/subject/pwrxrctx.html