jeudi 12 mars 2020

In Nock, URL seems ok to me but is not matched

I am trying to use nock to intercept a call from my app to the internet.

The goal here is to avoid using a variable external API when testing.

What I do is :

describe('My awesome test', () => {
    beforeEach(() => {
        let scope = nock('http://www.myexternalapi.eu')
            .log(console.log)
            .post('/my/awesome/path')
            .query(true)
            .reply(200, response);

        console.error('active mocks: %j', scope.activeMocks())
    });

    it('Should try to call my API but return always the same stuff ', () =>{
            myService.doStuffWithAHttpRequest('value', (success) => {
               // The answer must always be the same !
               console.log(success);
            });
    })

  // Other tests...

}

and myService.doStuffWithAHttpRequest('value', (success) is something like that :

    const body = "mybodyvalues";

    const options = {
        hostname: 'myexternalapi.eu',
        path: '/my/awesome/path',
        method: 'POST',
        headers: {
            'Content-Type': 'application/xml'
        }
    };

    const request = http.request(options, (response) => {
        let body = "";
        response.setEncoding('utf8');
        response.on('data', data => {
           body += data;
        });
        response.on('end', () => {
            parser.parseString(body, (error, result) => {
                // Do a lot of cool stuff
                onSuccess(aVarFromAllTheCoolStuff);
            });
        });
    });

When runing my tests, nock display this :

active mocks: ["POST http://www.myexternalapi.eu:80/my/awesome/path/"]

Seems good ! But my request is not matched and the external API is always called !

I have tried :

    beforeEach(() => {
        let scope = nock('http://www.myexternalapi.eu/my/awesome/path')
            .log(console.log)
            .post('/')
            .query(true)
            .reply(200, response);

        console.error('active mocks: %j', scope.activeMocks())
    });

It don't work neither.

    beforeEach(() => {
        let scope = nock('myexternalapi.eu')
            .log(console.log)
            .post('/my/awesome/path')
            .query(true)
            .reply(200, response);

        console.error('active mocks: %j', scope.activeMocks())
    });

It don't work neither and display a weird URL :

active mocks: ["POST null//null:443myexternalapi.eu:80/my/awesome/path/"]

Plus something is weird :

Nock can log matches if you pass in a log function like this:

    .log(console.log)

Do not display anything... ?! Any idea ?

Thanks you, I'm going crazy with this...

Aucun commentaire:

Enregistrer un commentaire