How to test html links with protractor?

2019-02-23 11:54发布

问题:

I am new to protractor and would like to test if a link is working. I understand trying to get the element id but what should i expect that the link equals?

Also has anyone got any good documentation on example protractor tests? I have been through this http://angular.github.io/protractor/#/tutorial which was helpful but i need more example of possible tests I could do.

i have this so far:

it('should redirect to the correct page', function(){
        element(by.id('signmein').click();
        expect(browser.driver.getCurrentUrl()).toEqual("http://localhost:8080/web/tfgm_customer/my-account");
    });

回答1:

would like to test if a link is working

This is a bit broad - it could mean the link to have an appropriate hrefattribute, or that after clicking a link there should be a new page opened.

To check the href attribute, use getAttribute():

expect(element(by.id('myLink')).getAttribute('href')).toEqual('http://myUrl.com');

To click the link use click(), to check the current URL, use getCurrentUrl():

element(by.id('myLink').click();
expect(browser.getCurrentUrl()).toEqual("http://myUrl.com");

Note that if there is a non-angular page opened after the click, you need to play around with ignoreSynchronization flag, see:

  • Non-angular page opened after a click

If the link is opened in a new tab, you need to switch to that window, check the URL and then switch back to the main window:

element(by.id('myLink')).click().then(function () {
    browser.getAllWindowHandles().then(function (handles) {
        browser.switchTo().window(handles[handles.length - 1]).then(function () {
            expect(browser.getCurrentUrl()).toEqual("http://myUrl.com");
        });

        // switch back to the main window
        browser.switchTo().window(handles[0]);
    });
});