Search code examples
javascriptnode.jsjestjssupertestnock

supertest mock with nock.back record mode not working


I have a nodejs service that when calling it's endpoint, does an http call to a service B. I'm adding an acceptance test to my service to test the integration.

Using nock.back in dryrun mode works perfectly but when I set the mode to record, the test doesn't work the second time I run it although the fixture is generated properly.

I need to run the tests in record mode because in some environments where the test will run, the service B won't be accessible.

Here is my test:

nock.back.setMode('record');
nock.back.fixtures = path.join(__dirname, '..', 'fixtures');

it('validates the contract for at least one hotel', (done) => {
  return nock
    .back('myfixture.json', defaultOptions)
    .then(({ nockDone }) =>
      request(app)
        .get('/myapi/route')
        .then((res) => {
          expect(res.status).toBe(200);
          console.log(res.body);
          done();
        })
        .then(nockDone),
    )
    .then();
});

When ran without the myfixture.json being generated before, the test passes and the fixture is generated properly. The next time I run the test (with the fixture there), the test fails with:

NetConnectNotAllowedError: Nock: Not allow net connect for "127.0.0.1:52027/myapi/route

On the other hand, if instead of record mode, I set dryrun mode, the test passes always and the body of the response is the correct so the calls to the service B are done properly.


Solution

  • The problem here is that the second time that the test runs with the fixtures already created, all the http requests that don't appear in the fixture files are denied.

    This denial also includes the actual internal requests that supertest does to the app so to solve it localhost must be allowed like:

    nock.enableNetConnect(/(localhost|127\.0\.0\.1)/);