Search code examples
javascriptintern

Functionally test that an Element is visible (no elements covering) with Intern


I am currently using the JavaScript framework Intern to test my site, I am wanting to ensure that specific element's are truly visible. Intern currently has an option "isDisplayed" which half does this. But what I am wanting to also do is check that it would be truly visible to the user and that any other elements on the page do not cover (perhaps by z-index issues) etc.

Does anyone have an suggestions?

Thanks in advance.


Solution

  • Usually, it's better to focus on your unit tests and make sure the styles you expect to be setting are coming back correctly from the utility/helper functions you use to do so. Otherwise, you're going to end up testing things you probably don't mean to, such as functionality of the browser itself to compute the styles. Therefor, it's bad practice in many situations.

    However, if you do need this, such as when testing a 3rd party JavaScript library against a customer's site, Intern's Leadfoot provides a .execute() method you'll want to use.

    Example:

    return this.remote      // represents the browser
        .get('mysite.com')  // navigate to a page
        .execute(           // send a callback to the browser
            function (selector) {
                var elem = document.querySelector(selector),
                    result;
                // collect some data for analysis...
                result = getComputedStyle(elem).zIndex;
                return result;
            },
            ['div']  // arguments to send to the remote callback
        )
        .then(
            function (zIndex) {
                // analyze the data and make assertions about it...
                assert(zIndex > 999);
            }
        );
    

    Please note: This is awesome but be careful. Most of your test runs inside of Node.js, but the callback to .execute() does not and so it does not have access to any of your previously defined variables, etc.

    As for strategies to determine when an element is truly visible to the user, it's very subjective, but getBoundingClientRect() is going to be your friend for determining when one element is overlapping another. There are good techniques here: Determine visibility / real z-index of html elements