Node + test: how to mock api using nock

Viewed 5051

Am trying to mock the api inside the unit test like the following:

const request = require('supertest');
const nock = require('nock');
const app = require('../app');

const agent = request.agent(app);
nock.disableNetConnect();
const userResponse = {
    user: {
      _id: '58828157ce4e140820e23648',
      info: {
        email: 'fake@test.io',
        password: '1',
        name: 'testx',
      },
};
  it('should register new user', (done) => {
    nock('http://localhost:5000')
      .post('/auth/register')
      .reply(200, userResponse);



    agent.post('/auth/register')
      .send({
        name: 'test',
        email: 'fake@test.io',
        password: '1',
      })
      .expect(200)
      .end((error, response) => {
        expect(response.body.user.info.email).to.equal('fake@test.io');
        expect(response.body.user.info.name).to.equal('test');
        done();
      });
  }).timeout(5000);

But am getting this error:

NetConnectNotAllowedError: Nock: Not allow net connect for "127.0.0.1:54877/auth/register"

2 Answers

If you want to allow requests to go to the internet for a certain domain, you can do:

const unBlockedDomains = ['toto.com', 'tata.fr'];
nock.enableNetConnect(host =>
  Boolean(unBlockedDomains.find(domain => host.includes(domain))),
);
Related