Search code examples
javascriptmockingautomated-testsweb-api-testingnock

Nock does not intercept call to 3rd party


I am trying to automate some REST services using SuperTest. The service is a POST call, which internally calls another third party service GET method. I am trying to mock third party services to improve test efficiency and reduce test execution time. I am using nock to mock the third party service call.

My initial service call looks like -

curl -X POST \
  http://internal-url.com/path \
  -H 'Content-Type: application/json' \
  -H 'cache-control: no-cache' \
  -d '{
    "key1": "value1",
    "key2": "value2"
}'

This service makes a call to the third party service which looks like -

curl -X GET \
  'http://3rdparty-url.com/value1' \
  -H 'Content-Type: application/json' \
  -H 'cache-control: no-cache' \
  -H 'key2: value2'

I have mocked the service using nock in beforeTest like -

nock('http://3rdparty-url.com')
    .get('/value1')
    .reply(200, 'domain matched');

When I make a call directly to this third party service using SuperTest, it is returning the mocked response. However, my objective is to make the POST call, and intercept call to the third party service with the stub, which is not happening. I have achieved similar thing in Java world using WireMock. Is it possible to do this using nock?

My test looks like -

var payload = {"key1": "value1", "key2": "value2"};
describe('Test third party Service', function () {
    it('should return success on POST /path service', function (done) {
        supertest('http://internal-url.com')
            .post('/path')
            .send(payload)
            .expect(200)
            .expect('Content-type', /application\/json/)
            .expect(function (response) {
                console.log(response.body);
                //test fails as third party server is not available and mock doesn't intercept
            })
            .end(done);
    });

Solution

  • Nock works by monkey-patching functions from Node's http and https modules in the memory of the current process. This means that the calls to Nock must be made in the same process as the one making the requests.

    In your case, whatever is running the app for "internal-url.com" needs to call nock. A common convention with nock and supertest is to run an instance of your internal app in the same process as the tests. Supertest examples show how to do this with a framework like Express.