34

I have a button on a page that looks like:

<button ng-click="myFunction()" ng-show="flag">
    Submit
</button>

The element has no ID.

Is there a way to find this element using the function bound to Ng-Click? Or do I have to assign an ID to this element to locate it using Jasmine / Protractor?

4 Answers 4

71

Just tested this and it works:

element(by.css('[ng-click="myFunction()"]'))
Sign up to request clarification or add additional context in comments.

8 Comments

confirm this. escape quotes (\") might be necessary.
IMHO, I think Lloyd Banks anwser is better. E2E tests are meant to test UI. They should rely on things visible to user, like button label "Submit", not the logic hidden in HTML attributes.
@matewka I would disagree, making it rely on text in the UI will be very fragile... And weather the user sees Submit, SUBMIT should not matter, and a simple uppercase can then break all your tests in a single go... Not to mention localisation... Ofc. on the flipside we need to ensure ng-click="submit()" isn't bound to our Cancel button...
I find the click then test that it has the text I expect to be displayed to the user. That way I fewer fragile UI-text based tests and get the back-end wiring validated.
If the function has parameters in the code, does my protractor test need to include those as well?
|
33

I went through the Protractor API and didn't find anything related to finding an element through ng-click. I did find

element(by.buttonText("Submit"));

Not quite the same, but does the job in my environment.

4 Comments

Although this works, it's worth noting that this isn't recommended by the protractor style guide. I think I would assign an ID to it so that it can be found easily.
It won't work if your button is a div or any non-button-type button.
@YuxuanChen Who said anything about a <div> or any other non <button> element? I like your enthusiasm for StackOverflow though. Keep up the hard work.
Exactly what I needed. I had a list of dynamic buttons being generated from a DB and my case required clicking a button by specific text as the text in question was not unique. i.e. [Admin] button vs [Administrator]. Finding a button by 'Admin' was troublesome. thank you
1

If you want to use ng-show, you could try this:

element(by.Css("button[ng-show]")); // Get element with tag < button > and has ng-show attribute

or:

element(by.Css("button[ng-show*=flag]")); // Get element with tag < button > and has ng-show attribute which contains word flag

Comments

0

Rather than adding an ID, which I don't like to do just to provide a test hook, I would add type="submit" to the button and then you can search By.css('[type="submit"]')

Comments

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.