0

I'm doing some testing for an AngularJS app, I don't think the test framework is necessarily important here, but I'm trying to pass an optional variable. This variable will specify if I'm trying to grab a child element of the ID that is passed to the function

commonFunctions.elementDoesNotHaveAttribute('register-0', 'disabled', 'children[0].children[0]');

the children[0].children[0] isn't really a string, if I remove the quotes the function call fails because it can't find a child object of .children[0]

Here is the function

function elementDoesNotHaveAttribute(id, attribute, child) {
    var hasElement = false;

    hasElement = casper.evaluate(function (id, attribute, child) {
        var element = document.getElementById(id);
        if (child) {
            element = element.child;
        }        
        return element.hasAttribute(attribute);
    }, id, attribute, child);

    if (hasElement) {
        casper.test.fail('element has' + attribute + ' but shouldn\'t');
    } else {
        casper.test.pass('element didn\'t have ' + attribute + ' and shouldn\'t');
    }
}

How can I change either side of these equations to end up evaluating element.children[0].children[0] within my function

2
  • that worked, I haven't used eval() much in the past Commented Feb 22, 2016 at 16:39
  • @T.J.Crowder, it is taking an ID, attribute, and optionally a child element. It is checking to see if that selector as the attribute that is passed or not Commented Feb 22, 2016 at 16:51

1 Answer 1

2

While the "eval hack" I posted in a comment will work, it's a bad idea. Instead, consider passing some kind of "transformation" function.

if( child) {
    element = child(element);
}

When calling for, say, children[0].children[0], you can do this:

commonFunctions.elementDoesNotHaveAttribute(
    'register-0',
    'disabled',
    function(e) {return e.children[0].children[0];}
);

The function will take the element and return something else related to it. Adjust the function as needed.

Sign up to request clarification or add additional context in comments.

3 Comments

Good solution, and well done understanding the question, too. :-)
Works great, thanks for the tip. I like the solution
Niet, I suggest cleaning up the comments on the question. (This comment will self-destruct in five...four...three...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.