如何使用 Nock、Node js 在单元测试中模拟一行

How to mock a line in unit test using Nock, Node js

我试图在单元测试中注入一行但失败了,它似乎遇到了一个真正的请求,以下代码是 football api 的一部分,我需要模拟其中的最后一行文件

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

看来我误解了诺克的作用。 这就是 Nock 的工作原理。

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

我们的主机是: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 将像 charm 一样工作,否则它会抛出异常 Nock 不匹配特定 URL