Ahmed
Ahmed

Reputation: 51

Couldn't nock a function call

I had a problem when wanting to unit test a function that launch a http request and gets data. The request is intercepted but the function does not receive what I defined in the .reply() clause of the nock function. I have been struggling for hours without any clue of where the problem is !!!

This is my function:

import request from 'request';
import { pick, map } from 'lodash';
import { logger, getEnv } from './utils';


export default function getStoresFromProductDB() {
  const dataToPick = [
    'iccli',
    'store_name',
  ];
  const host = 'http://localhost:4001';
  const url = `${host}/store`;
  logger.info(`Getting stores from product DB at URL ${url}`);

  return new Promise((resolve, reject) => {
    request(url, { json: true }, (err, res, body) => {
      if (err) {
        reject(err);
      } else {
        const { data } = body;
        resolve(map(data, store => pick(store, dataToPick)));
      }
    });
  });
}

And this my test code :

describe('Testing getting stores from product database', () => {
  it('should return 200 and the list of available stores from product database', async () => {
    nock('http://localhost:4001')
      .get('/store')
      .reply(200, stores);

    const data = await getStoresFromProductDB();
    console.log('​data', data);
  });
});

Can you help me please ?

Upvotes: 1

Views: 521

Answers (1)

Ahmed
Ahmed

Reputation: 51

oh man, I solved the problem, it was about the data format that is replied by nock. Because the getStoresFromProductDB function was expecting an object wich has a data array inside it which hold the data I want to fetch, so it is an array inside of an object, and I was replying directly an array. That was stupid.

So the test code must be like this :

describe('Testing getting stores from product database', () => {
  it('should return 200 and the list of available stores from product database', async () => {
    nock('http://localhost:4001')
      .get('/store')
      .reply(200, { data: stores });

    const data = await getStoresFromProductDB();
    console.log('​data', data);
  });
});

Upvotes: 1

Related Questions