【问题标题】:How to mock a line in unit test using Nock, Node js如何使用 Nock、Node js 在单元测试中模拟一行
【发布时间】:2018-08-29 09:35:44
【问题描述】:

我试图在单元测试中注入一行我失败了,它似乎达到了一个真正的请求,下面的代码是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);
  });
});

【问题讨论】:

    标签: node.js unit-testing chai nock


    【解决方案1】:

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

    1. 您需要模拟主机网址。
    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 将像魅力一样工作,否则它会抛出异常 Nock not match for the specific URL

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-05-04
      • 2018-11-03
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多