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

I am working on automating an end-to-end script using Mocha. I have a url endpoint that needs to be polled until a specific value is received in the received response. Is there any way to do this?

+6
source share
2 answers

Example with request and callback:

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 / wait 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'));
    });
});
+5
source

Here is how I was able to do this with WebdriverIO and Mocha

describe("wait for value in content of page", () => {
    it("should be able to wait to value in url", () => {

      var max_seconds_to_wait = 10;
      var seconds_counter = 0;
      var should_continue = true;

      while (should_continue) {

         browser.url('http://your.url.com');
         var response = JSON.parse(browser.getText("body"));
         console.log(response)

         if (response == 'something') {
             should_continue = false;              
         }
         browser.pause(1000);
         seconds_counter++;

         if (seconds_counter > max_seconds_to_wait) {
             throw 'Waiting for json from url timeout error';
         }
     }
   });
});
-1
source

All Articles