Search code examples
node.jsunit-testingchainock

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


I'm trying to inject one line in unit test i got failed, it seems that it hits a real request, the following code is part of football api and i need to mock the last line in this file

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

and here is the mock which i tried

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

Solution

  • It seems that i misunderstood what Nock does. This is how Nock works.

    1. you will need to mock the host url.
    2. you will need to mock the path, use any http method but it should be exactly as existing url even the query parameters.
    3. after that Nock will try to combine them and see if there is a url matched for example

    our host is : http://www.example.com

    our path is : /uuid/training

    then we should do something like that

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

    now if the Nock see matched url the Nock will work like charm otherwise it will throw an exception Nock not matched for the specific URL