Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polling a URL until certain value is set in JSON response : Mocha, Integration testing

I am working on automating an End to end scenario using Mocha. I have a url endpoint which is to be polled until a certain value is obtained in the resulting response. Is there any way to do it ?

like image 671
Thiruveni Balasubramanian Avatar asked Sep 12 '17 06:09

Thiruveni Balasubramanian


1 Answers

Example with request and callback approach:

const request = require('request');

describe('example', () => {
    it('polling', function (done) {
        this.timeout(5000);

        let attemptsLeft = 10;
        const expectedValue = '42';
        const delayBetweenRequest = 100;

        function check() {
            request('http://www.google.com', (error, response, body) => {
                if (body === expectedValue) return done();
                attemptsLeft -= 1;
                if (!attemptsLeft) return done(new Error('All attempts used'));
                setTimeout(check, delayBetweenRequest);
            });
        }

        check();
    });
});

Example with got and async/await approach:

const utils = require('util');
const got = require('got');

const wait = utils.promisify(setTimeout);

describe('example', () => {
    it('polling', async function (done) {
        this.timeout(5000);
        const expectedValue = '42';
        const delayBetweenRequest = 100;

        for (let attemptsLeft = 10; attemptsLeft; attemptsLeft -= 1) {
            const resp = await got.get('http://www.google.com');
            if (resp.body === expectedValue) return done();
            await wait(delayBetweenRequest);
        }

        done(new Error('All attempts used'));
    });
});
like image 158
galkin Avatar answered Nov 15 '22 05:11

galkin