Search code examples
javascripttestingintern

Test async page changes with the intern


Lets say I have a button and a div element on a page.

<button /><div>old text</div>

By clicking on button, javascript asynchronously change the text of the div (i.e. after ajax call). How can i test it with intern?

This does not work:

function testButtonClick() {
      return command
                 .findByTagName('button')
                 .click()
                 .end()
                 .findByTagName('div')
                 .getVisibleText()
                 .then(function(text) { assert.strictEqual(text,'new text')}); //errror, text is 'old text'
}

If I add .sleep(5000) after .end(), then it works Ok (because my async request is usually done in 5 seconds). But I do not want to wait so long, because the async is usually finished much earlier.

But using sleep with lower time value, I risk that it will be tested before the request is finished.

Is there a better way?


Solution

  • The most efficient solution would be to use pollUntil, something like:

    return command
        .findByTagName('button')
        .click()
        .end()
        .then(pollUntil(function () {
            var el = document.getElementByName('div');
            if (el && el.textContent === 'new text') {
                return true;
            }
        }, 5000));
    

    Poll until will run a function in the browser context repeatedly until it returns a non-null, non-undefined answer, or until it times out. In the snippet above the polling function returns true if the element exists and has the expected text, or undefined otherwise. It will timeout after 5000ms, but it will end as soon as the expected text shows up.