首页 > 解决方案 > 在 nodejs 中拦截外部 API 调用

问题描述

js),我想使用 mocha 和 chai 正常测试它,但是 API 依赖于我想模拟的外部服务。是否可以模拟以下内部调用,例如以清晰显示:

describe('account Link', function() {
    it('should return with account status', async function(done) {
      nock('http://api.github.com', { allowUnmocked: true })
      .get('/users/AKGP')
      .reply(200, 
        {
          test: true
        });

     const options = {
       uri: 'http://localhost:3000/internal_api',
       body: {},
       headers: {
         'content-type': 'application/json'
       },
       method: 'POST',
       json: true
     }
     try {
      const res = await rp(options)
      console.log(res)
      done();
     } catch(err){
       console.log(err);
       done();
     }
    });
  });

// the nocked api is called internally and I am expecting to mock it (http://api.github.com)

标签: javascriptnode.jsmocha.jschainock

解决方案


推荐阅读