concept web element in category angular

appears as: web elements, web element, web elements
Testing Angular Applications

This is an excerpt from Manning's book Testing Angular Applications.

Listing 8.8 Test to create another contact—e2e/add-second-contact.e2e-spec.ts
import { browser, by, element } from 'protractor';

describe('adding a new contact with name, email,' + 
    'and phone number', () => {
  beforeAll(() => {
    browser.get('/#/');
    element(by.id('add-contact')).click();
    element(by.id('contact-name')).sendKeys('Grace');
  });

  it('should type in an email address', () => {
 let email = element(by.id('contact-email'));    #1  
 email.sendKeys('grace@hopper.com');    #2  
    expect(email.getAttribute('value'))
        .toEqual('grace@hopper.com');
  });

  it('should type in a phone number', () => {
 let tel = element(by.css('input[type="tel"]'));    #3  
    tel.sendKeys('1234567890');
    expect(tel.getAttribute('value'))
        .toEqual('1234567890');
  });

  it('should click the create button', () => {
    element(by.css('.create-button')).click();
    expect(browser.getCurrentUrl())
        .toEqual(browser.baseUrl + '/#/');
  });
});

#1   When declaring the element, WebDriver doesn’t search the browser for the web element.
#2   When an action is called, Protractor locates the web element on the screen and sends the string to the input field.
#3   Locates the web element by using the css class

In listing 8.9, the test enters a valid name and an invalid email address, baduser.com. After the test clicks the Create button, it should check if the modal alert window is visible and dismiss the message. After dismissing the modal alert message, it’s a good idea to verify that the modal alert did disappear. To test this, you can use another Protractor API called ExpectedConditions. The ExpectedConditions API combined with the browser.wait method allows the test to wait for some condition to occur on the web application within a set period of time. In this example, you’re waiting for the web element to not be present within five seconds. Finally, because the test should fail to create a new contact, the test also should check to see if the Contacts app route URL is still on the /#/add route.

Let’s consider a different scenario where you need to test all the contacts on the contact list. Instead of writing a filter function for each contact, you could use the map function. The map function converts the web elements returned from the element.all to an array shown in figure 8.6.

Figure 8.6 Convert the web elements to an array using the map function

c08_06.png