轮询一个URL,直到在JSON响应中设置了一定的值:Mocha,集成testing

我正在使用Mocha自动化端到端场景。 我有一个url端点被轮询,直到得到一个特定的值在得到的响应。 有没有办法做到这一点?

       

网上收集的解决方案 "轮询一个URL,直到在JSON响应中设置了一定的值:Mocha,集成testing"

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

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

这就是我通过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'; } } }); });