Controlador IO Tutorial usando un sitio Web de web y ejemplos de trabajo (5 / 8 paso)

Paso 5: Ejemplos concretos

Todo el código está disponible en github: Web controlador IO Tutorial en github

  • Verificar el enlace y enlace de texto en una lista desordenada - "linkTextURL1.js"

    • La lista desordenada tiene un id = "mylist" y el enlace es el 4 º elemento de la lista.
    • La URL debe ser "http://tlkeith.com/contact.html"
 // Verify Contact Us link text it('should contain Contact Us link text', function () { return driver .getText("//ul[ (link) { console.log('Link found: ' + link); (link).should.equal("Contact Us"); }); }); // Verify Contact Us URL it('should contain Contact Us URL', function () { return driver .getAttribute("//ul[ "href").then(function (link) { (link).should.equal("http://tlkeith.com/contact.html"); console.log('URL found: ' + link); }); }); 
  • Verificar el texto de derechos de autor - "Copyright1.js"

    • Los derechos de autor está en el footerThis ejemplo muestra 2 formas diferentes para localizar el texto de derechos de autor:

      • por el id = "copyright" como el selector del elemento
      • mediante el uso de xpath como el selector del elemento
 // Verify Copyright text using id as element selector it('should contain Copyright text', function () { return driver .getText("#copyright").then(function (link) { console.log('Copyright found: ' + link); (link).should.equal("Tony Keith - tlkeith.com @ 2015 - All rights reserved."); }); }); // Verify Copyright text using xpath as element selector it('should contain Copyright text', function () { return driver .getText("//footer/center/p").then(function (link) { console.log('Copyright found: ' + link); (link).should.equal("Tony Keith - tlkeith.com @ 2015 - All rights reserved."); }); }); 
  • Rellenar campos de formulario y enviar - "formFillSubmit1.js"

    • Rellene el nombre, apellidos y enviar, luego espere resultados.
    • Este ejemplo muestra 3 métodos de llenar el campo Nombre:
      • por id
      • por xpath de entrada
      • por xpath de forma -> entrada
    • También muestra cómo borrar un campo de entrada
 // Set the first name using id to: Tony it('should set first name to Tony', function () { return driver.setValue("#fname", "Tony") .getValue("#fname").then( function (e) { (e).should.be.equal("Tony"); console.log("First Name: " + e); }); }); // Clear the first name using id it('should clear first name', function () { return driver.clearElement("#fname") .getValue("#fname").then( function (e) { (e).should.be.equal(""); console.log("First Name: " + e); }); }); // Set the first name using xpath from input to: Tony it('should set first name to Tony', function () { return driver.setValue("//input[ "Tony") .getValue("//input[ function (e) { (e).should.be.equal("Tony"); console.log("First Name: " + e); }); }); // Clear the first name using xpath from input it('should clear first name', function () { return driver.clearElement("//input[ .getValue("//input[ function (e) { (e).should.be.equal(""); console.log("First Name: " + e); }); }); // Set the first name using xpath from form to: Tony it('should set first name to Tony', function () { return driver.setValue("//form[ "Tony") .getValue("//form[ function (e) { (e).should.be.equal("Tony"); console.log("First Name: " + e); }); }); // Set the last name using id to: Keith it('should set last name to Keith', function () { return driver.setValue("#lname", "Keith") .getValue("#lname").then( function (e) { (e).should.be.equal("Keith"); console.log("Last Name: " + e); }); }); // Submit form and wait for search results it('should submit form and wait for results', function () { return driver.submitForm("#search-form").then( function(e) { console.log('Submit Search Form'); }) .waitForVisible("#search-results", 10000).then(function (e) { console.log('Search Results Found'); }); }); 
  • Haga clic en el botón de mostrar u ocultar y verificar el texto - "showHideVerify1.js"

    • El texto es un elemento de mostrar u ocultar. El botón controla el estado.
    • Este ejemplo se muestra:
      • Haga clic en el botón ampliar
      • Espere a que el elemento sea visible (ampliado)
      • Comprobar texto (copia cubierta)
 // click "More Info" button and verify text in expanded element it('should click more info button and verify text', function () { return driver .click("#moreinfo").then (function () { console.log('Clicked More Info button'); }) .waitForVisible("#collapseExample", 5000) .getText("//div[ (function (e) { console.log('Text: ' + e); (e).should.be.equal("All things good go here!"); }); }); 
  • Validar formulario campo errores - "formFieldValidation.js"

    • Utilizar scripts de prueba para comprobar que se producen mensajes de error correcto.
    • Este ejemplo se muestra:
      • Verificar los mensajes de texto de error y verificar ubicación (posición de lista desordenada).
 it('should contain 5 errors: first/last/address/city/state', function () { return driver .getText("//ul[ alert-danger']/li[1]").then(function (e) { console.log('Error found: ' + e); (e).should.be.equal('Please enter first name'); }) .getText("//ul[ alert-danger']/li[2]").then(function (e) { console.log('Error found: ' + e); (e).should.be.equal('Please enter last name'); }) .getText("//ul[ alert-danger']/li[3]").then(function (e) { console.log('Error found: ' + e); (e).should.be.equal('Please enter address'); }) .getText("//ul[ alert-danger']/li[4]").then(function (e) { console.log('Error found: ' + e); (e).should.be.equal('Please enter city'); }) .getText("//ul[ alert-danger']/li[5]").then(function (e) { console.log('Error found: ' + e); (e).should.be.equal('Please enter state'); }); }); 
  • Bucle de datos para validar URL página de texto de enlace - "LoopDataExample1.js"

    • Este ejemplo muestra: utilice una matriz de datos JSON para guardar el enlace y el nombre, luego iterar

  • Verificar cada texto de la URL y el enlace
  • Haz clic en el enlace y cargar la página
Vincular datos - link y texto var linkArray = [{"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/tutorial1.js", "nombre": "tutorial1.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/linkTextURL1.js", "nombre": "linkTextURL1.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/copyright1.js", "nombre": "copyright1.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/formFillSubmit1.js", "nombre": "formFillSubmit1.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/showHideVerify1.js", "nombre": "showHideVerify1.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/dynamicBrowser.js" "nombre": "dynamicBrowser.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/callbackPromise.js", "nombre": "callbackPromise.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/debugExample1.js", "nombre": "debugExample1.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/formFieldValidation.js", "nombre": "formFieldValidation.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/common/commonLib.js", "nombre": "commonLib.js"}, {"link": "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/dataLoopExample1.js", "nombre": "dataLoopExample1.js"}]; ... / / bucle por cada linkArray.forEach(function(d) de linkArray {('debe contener la página de enlace de texto a continuación, goto -' + d.name, function() {controlador de retorno / / asegurarse de que estás en la página de inicio // Link data - link and text var linkArray = [ {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/tutorial1.js", "name" : "tutorial1.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/linkTextURL1.js", "name" : "linkTextURL1.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/copyright1.js", "name" : "copyright1.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/formFillSubmit1.js", "name" : "formFillSubmit1.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/showHideVerify1.js", "name" : "showHideVerify1.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/dynamicBrowser.js", "name" : "dynamicBrowser.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/callbackPromise.js", "name" : "callbackPromise.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/debugExample1.js", "name" : "debugExample1.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/formFieldValidation.js", "name" : "formFieldValidation.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/common/commonLib.js", "name" : "commonLib.js"}, {"link" : "https://github.com/onewithhammer/WebDriverIOTutorial/blob/master/dataLoopExample1.js", "name" : "dataLoopExample1.js"} ]; ... // loop through each linkArray linkArray.forEach(function(d) { it('should contain text/link then goto page - ' + d.name, function() { return driver // make sure you are on the starting page .url('http://www.tlkeith.com/WebDriverIOTutorialTest.html') .getTitle().then( function (title) { // verify title (title).should.be.equal("Web Driver IO - Tutorial Test Page"); }) // find the URL .getAttribute('a=' + d.name, "href").then(function (link) { (link).should.equal(d.link); console.log('URL found: ' + d.link); }) // go to URL page and verify it exists .click('a=' + d.name) .waitForVisible("#js-repo-pjax-container", 10000).then(function () { console.log('Github Page Found'); }); }); }); .getTitle () entonces (función (título) {/ / comprobar título // data array - firstName and lastName<br>var dataArray = [ {"firstName" : "Tony", "lastName" : "Keith"}, {"firstName" : "John", "lastName" : "Doe"}, {"firstName" : "Jane", "lastName" : "Doe"}, {"firstName" : "Don", "lastName" : "Johnson"} ]; ... // loop through each dataArray <br> dataArray.forEach(function(d) { it('should populate fields, sumbit page', function() { return driver // make sure you are on the starting page .url('http://www.tlkeith.com/WebDriverIOTutorialTest.html') .getTitle().then( function (title) { // verify title (title).should.be.equal("Web Driver IO - Tutorial Test Page"); }) .setValue("#fname", d.firstName) .getValue("#fname").then( function (e) { (e).should.be.equal(d.firstName); console.log("First Name: " + e); }) .setValue("#lname", d.lastName) .getValue("#lname").then( function (e) { (e).should.be.equal(d.lastName); console.log("Last Name: " + e); }) .submitForm("#search-form").then( function() { console.log('Submit Search Form'); }) .waitForVisible("#search-results", 10000).then(function () { console.log('Result Page Found'); }) .getText("//h1").then(function (link) { console.log('Text found: ' + link); (link).should.equal("Welcome " + d.firstName + " " + d.lastName + "."); }); }); }); 
  • Datos estáticos de bucle para rellenar campos de formulario - "loopDataExample2.js"

    • Este ejemplo muestra: utilice una matriz de datos JSON para almacenar el nombre primera/última

      • Recorrer los datos a rellenar campos de formulario, a continuación, enviar el formulario
      • Espere la página resultados
      • Verificar primero / último nombre en la página de resultados
matriz de datos - firstName y lastName < br > var dataArray = [{"nombre": "Tony", "apellido": "Keith"}, {"nombre": "John", "apellido": "Doe"}, {"nombre": "Jane", "apellido": "Doe"}, {"nombre": "Don", "apellido": "Johnson"}]; ... / / bucle por cada dataArray < br > dataArray.forEach(function(d) {('debe rellenar los campos, Enviar página', function() {conductor de retorno / / asegurarse de que estás en la página de inicio it('should contain correct color of error text', function () {<br> return driver .getCssProperty("//ul[ alert-danger']/li[1]", "color").then(function (result) { console.log('Color found: ' + result.parsed.hex + " or " + result.value); (result.parsed.hex).should.be.equal('#a94442'); }); }); .getTitle () entonces (función (título) {/ / comprobar título it('should contain correct padding in table cell', function () { return driver // padding: top right bottom left .getCssProperty("//table[ "padding-top").then(function (result) { console.log('padding-top found: ' + result.value); (result.value).should.be.equal('10px'); }) .getCssProperty("//table[ "padding-bottom").then(function (result) { console.log('padding-bottom found: ' + result.value); (result.value).should.be.equal('10px'); }) .getCssProperty("//table[ "padding-right").then(function (result) { console.log('padding-right found: ' + result.value); (result.value).should.be.equal('5px'); }) .getCssProperty("//table[ "padding-left").then(function (result) { console.log('padding-left found: ' + result.value); (result.value).should.be.equal('5px'); }); }); 
  • Validar CSS propiedades - "cssValidation1.js"

    • Este ejemplo muestra cómo:

      • Validar las siguientes propiedades CSS:

        • Color
        • acolchado (superior, inferior, derecha, izquierda)
        • color de fondo
 it('should contain correct background color in table header', function () { return driver .getCssProperty("//table[ "background-color").then(function (result) { console.log('background color found: ' + result.parsed.hex); (result.parsed.hex).should.be.equal('#eeeeee'); }); }); 
 driver = webdriverio.remote(loglevel: 'verbose', logOutput: 'logs', {desiredCapabilities: {browserName: 'firefox'} });<br> 
 // Click on the Item 3 from list it('should click on Item 3 from list', function () { // use getText() to verify the xpath is correct for the element return driver .getText("//ul[ (link) { // use console.log() to output information console.log('Link found: ' + link); (link).should.equal("Item 3"); }) // use debug() to stop action to see what is happening on the browser .debug() .click("//ul[ (function () { console.log('Link clicked'); }) // wait for google search form to appear .waitForVisible("#tsf", 20000).then(function (e) { console.log('Search Results Found'); }); }); 

Artículos Relacionados

Crear un sitio web utilizando iWeb

Crear un sitio web utilizando iWeb

sitios web son una forma sencilla de informar al público sobre su tema de interés. En este tutorial crearemos un sitio web de fitness con el programa iWeb. Usted puede hacer una página web sobre cualquier tema de su elección. Con un sitio web de fitn
Cómo crear un sitio web compartido usando Shutterfly.com

Cómo crear un sitio web compartido usando Shutterfly.com

Shutterfly ofrece una característica de participación donde los miembros pueden crear y publicar sitios Web. Un componente popular a la función de compartir es la Web de aula. Maestros pueden invitar a los padres para ver fotos, revisar calendarios y
Cómo hacer un sitio web usando weebly.com

Cómo hacer un sitio web usando weebly.com

Le enseñará cómo hacer sitios web [nuestra empresa] usando weebly.comPaso 1: RegistrarseSubir a weebly.com y firmar con tu correo electrónico [inicio de sesión con información de la empresa].Paso 2: Agregar o hacer un sitio webSi usted está firmando
Para principiantes hackers Tutorial Ep.2: Remotamente cerrar un sitio Web

Para principiantes hackers Tutorial Ep.2: Remotamente cerrar un sitio Web

* AVISO LEGAL *ESTA TÉCNICA YA NO FUNCIONA.En primer lugar quiero ir al menú Inicio y escriba SHUTDOWN-I y pulse enter y el programa debe abrirPaso 1: Principiante Hacker Tutorial Ep.2: remotamente cierre abajo de un sitio web Ahora, vas a necesitar
Formación de E-Commerce: Aprender a construir un sitio web de comercio electrónico usando software libre

Formación de E-Commerce: Aprender a construir un sitio web de comercio electrónico usando software libre

originalmente llamé a este curso el curso de capacitación de 4 horas e-commerce. Yo le pagado-para la formación en una base del webinar. Aunque menos de un año de edad, los materiales ya están un poco fuera de fecha, así que no puedo realmente cobrar
Cómo transmitir el eclipse solar a un sitio web con una webcam USB (código de C#) 20 de marzo de 2015

Cómo transmitir el eclipse solar a un sitio web con una webcam USB (código de C#) 20 de marzo de 2015

C# fuente de código para la transmisión de imagen para sitios web - no sólo en el 20 de marzo de 2015!Este artículo muestra cómo ver el eclipse solar segura el 20 de marzo en su PC mediante el uso de un simple USB webcamera. Es un C#-solución base qu
Crear un botón de lanzamiento del sitio web enorme, intermitente,

Crear un botón de lanzamiento del sitio web enorme, intermitente,

En hybris, acabamos de lanzar nuestro nuevo comercio cloud API en yaas.io. El equipo de labs de hybris apoyó el público arranque con un botón de lanzamiento frío. Es un botón grande cúpula estilo arcade, tiene un LED integrado así que usted puede dej
Hospedar su sitio web en frambuesa pi

Hospedar su sitio web en frambuesa pi

frambuesa pi es un tablero de bajo costo de desarrollo por la Fundación frambuesa, para este tutorial estoy usando la distro por adafruit que puede encontrar en http://learn.adafruit.com/adafruit-raspberry-pi-educational-linux-distro/occidentalis-v0-
Construir un sitio web para tan poco como $20 años!

Construir un sitio web para tan poco como $20 años!

En este instructable, va cubriendo todo lo que necesitas saber para crear un gran sitio web a muy bajo costo! Si desea ver algunos de mis trabajos, visitad: Webshawty.comUn par de cosas que tienes que:-Acceso a Internet-Una nueva computadoraOtros mat
Cómo construir tu propio sitio Web

Cómo construir tu propio sitio Web

una guía completamente cubierta para conseguir desde el papel hasta la web, gratis si lo desea, especialmente si cualquier webmasters amistoso deberle favores a pocos pero aún con poca experiencia y conocimiento puede construir un sitio web y consegu
Construir un sitio web profesional: parte 2

Construir un sitio web profesional: parte 2

esta es la segunda serie de las lecciones de punto en diseño web. Si eres nuevo en diseño web o la necesidad de volver a tapar, por favor informe: construir un sitio web profesional: parte 1Código HTML y los códigos de color son en este instructable:
Servidor gratuito alojado sitio web (Dropbox, GitHub, DNSPOD y Freenom)

Servidor gratuito alojado sitio web (Dropbox, GitHub, DNSPOD y Freenom)

Este tutorial mostrará cómo hospedar su sitio web en dos servidores independientes (una principal y una copia de seguridad) de esta forma que su sitio de Internet casi siempre estará en línea. A través de DNS de terceros te reenvío serán capaces de t
Construir tu propio sitio web con dreamweaver

Construir tu propio sitio web con dreamweaver

por lo que previamente he escrito sobre esto antes, el viejo es digno de la lectura en primer lugar, contiene instrucciones en photoshop y dreamweaver que esto no, sin embargo falta mucho señala respecto a este.Estos días hay toneladas de servicios p
Arduino Esp8266 Post datos al sitio Web

Arduino Esp8266 Post datos al sitio Web

El módulo de WiFi de ESP8266 es un autónomo SOC con pila de protocolo TCP/IP integrado que puede dar cualquier microcontrolador el acceso a tu red WiFi. Ofrece una completa y autónoma Wi-Fi networking solución, permitiendo organizar ya sea la aplicac