轮询URL直到在JSON响应中设置特定值:Mocha,Integration testing

时间:2017-09-12 06:32:56

标签: node.js mocha integration

我正在使用Mocha自动化端到端场景。 我有一个url端点,它将被轮询,直到在结果响应中获得某个值。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:5)

request示例和回调方法:

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();
    });
});

got和async / await方法的示例:

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'));
    });
});

答案 1 :(得分:-1)

这就是我用WebdriverIO和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';
         }
     }
   });
});