如何使用Nock,Node js

时间:2018-08-29 09:35:45

标签: node.js unit-testing chai nock

我试图在单元测试中插入一行失败的代码,看来它遇到了真正的请求,以下代码是football api的一部分,我需要模拟该文件中的最后一行< / p>

module.exports.getSummary = async ({ uuid, market}) => {
  const { countryCode } = AppConfigs.Markets[market];
  let url = `${host}${getSummary}`;

  url = url.replace('[market]', countryCode);
  url = url.replace('[uuid]', uuid);
  Log.debug('Getting Summary Info from football API', { url }, 'Subscription::index', 'info');

 // this line which i need to inject
  const result = await Helpers.http.get({}, url, undefined);

  return result;
};

这是我尝试过的模拟游戏

const chai = require('chai');
const nock = require('nock');

const FootballApi = require('../../server/services/football/index');
const SummaryMock = require('./getSummary.mock');

const { expect } = chai;

describe('get Summary', () => {
  it('Should return null', async () => {
    before(() => {
      const { req, res } = SummaryMock.getSummary;

      const mock = nock(FootballApi.getSummary(req));
      mock.get(req.path).reply(200, res);
    });

    const { res } = SummaryMock.getSummary;
    const response = await FootballApi.getSummary(SummaryMock.getSummary.req);
    console.log(response);
    console.log(res);
  });
});

1 个答案:

答案 0 :(得分:1)

似乎我误解了诺克的所作所为。 这就是Nock的工作方式。

  1. 您将需要模拟主机网址。
  2. 您将需要模拟路径,使用任何http方法,但是它应该与 现有网址,甚至是查询参数。
  3. 之后,Nock会尝试将它们组合起来,看看是否有匹配的网址 例如

我们的主机是:http://www.example.com

我们的路径是:/uuid/training

然后我们应该做类似的事情

 const mockHttp = nock(training.baseUrl); //mock the http
 mockHttp.get(ourPath).reply(200, ourBody); //mock exact path

现在,如果Nock看到匹配的URL,则Nock会像魅力一样工作,否则它将抛出与特定URL不匹配的Nock异常