You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
12 Hrs
54 Min
48 Seg

M谩s sobre selectores

6/17
Resources

Test Planning

When developing any test that you wish to evaluate, you must take into consideration the context with which the feature or module is encountered.

For example:

  • In a component test, we wish to evaluate the functionality according to its contribution, be it on a page or section layout.
  • On the other hand, in an E2E (End-2-End, Point-to-End) test, we seek to evaluate a whole according to the requirements imposed by our user stories.

Regardless of the case, the anatomy of the tests must be taken into consideration in order to have a guide and establish a working structure.

Writing E2E tests

Suppose we have a list of activities (TODO List). In it, we wish to evaluate that:

  • Given a new activity, in an empty list, it should be displayed once entered.
  • Given a new activity, in a list with at least 1 activity, it should be displayed at the end of the list.

From the above, let's consider:

  1. Manage the Playwright configuration to pre-set the base path:

    export default defineConfig({ // ... use: { // ... baseURL: "https://demo.playwright.dev", // ... }, // ... })

  2. Define the cycle hooks of our test pool:

    ``` import { test, expect, type Page } from '@playwright/test'.

    test.beforeEach(async ({ page }) => { await page.goto('/todomvc') }) ````

  3. Set or require some mock(s) to evaluate our cases:

    ```` import { test, expect, type Page } from '@playwright/test' import todoItems from './mocks/todoItems.mock.ts'

    test.beforeEach(async ({ page }) => { await page.goto('/todomvc') }) ````

    export default [ 'Clean the house', 'Feed the dog' ]

  4. Group and define our test cases

    ```` import { test, expect } from '@playwright/test' import todoItems from './mocks/todoItems.mock.ts'

    test.beforeEach(async ({ page }) => { await page.goto('/todomvc') })

    test.describe('TODO app', () => { test('should be able to add a new item', async ({ page }) => { // Input activity // Validate text item }) test('should append the last items added to the bottom of the list', async ({ page }) => { // Input activity // Validate text item }) }) ````.

  5. Completing the test cases

    ``` import { test, expect, type Page } from '@playwright/test' import todoItems from './mocks/todoItems.mock.ts'

    test.beforeEach(async ({ page }) => { await page.goto('/todomvc') });

    test.describe('TODO app', () => { test('should be able to add a new item', async ({ page }) => { const newTodo = page.getByPlaceholder('What needs to be done?') await newTodo.fill(todoItems[0]) await newTodo.press('Enter') await expect(page.getByTestId('todo-title')).toHaveText(todoItems[0]) }) test('should append the last items added to the bottom of the list', async ({ page, }) => { const newTodo = page.getByPlaceholder('What needs to be done?') await newTodo.fill(todoItems[0]) await newTodo.press('Enter') await newTodo.fill(todoItems[1]) await newTodo.press('Enter') await expect(page.getByTestId('todo-item').nth(1)).toHaveText(todoItems[1]) }); }); ````; ```

Contribution created by: Emmanuel Rodriguez

Contributions 5

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Tambien se puede seleccionar el elemento por sus propiedades, lo cual nos ayuda con la especificidad. En este caso, es comun que cada etiqueta <a> nos lleve a distintas paginas, osea que tengan una propiedad unica de href. Para acceder al link de UITAP, podemos usar el siguiente selector:

await page.locator("a[href='/']")

Sin embargo esto no siempre es verdad, ya que a veces hay dos links en una misma pagina que nos llevan a un mismo lugar, en este caso ya podemos usar otras propiedades como las clases de css. Por ejemplo, si quisieramos ser mas especificos con el selector de arriba, se puede hacer de la siguiente manera:

await page.locator("a.navbar-brand[href='/']")

Desarrollo de Pruebas

Al desarrollar cualquier prueba que se desee evaluar, se debe tomar a consideraci贸n el contexto con el que la caracter铆stica o m贸dulo se encuentra.
.
Por ejemplo:

  • En una prueba de componente, deseamos evaluar la funcionalidad seg煤n su aportaci贸n, sea en una p谩gina o distribuci贸n de un secci贸n.
  • Por su parte, en una prueba E2E (End-2-End, Punto a punto), buscamos evaluar un todo seg煤n los requerimientos impuestos por nuestras historias de usuario.

.
Sin importar el caso, se debe tomar a consideraci贸n la anatom铆a de las pruebas para tener una gu铆a y establecer una estructura de trabajo.
.

Redactando pruebas E2E

Supongamos que tenemos una lista de actividades (TODO List). En ella, deseamos evaluar que:

  • Dada una nueva actividad, en una lista vac铆a, se deber谩 mostrarse una vez ingresada
  • Dada una nueva activad, en una lista con al menos 1 actividad, se deber谩 mostrarse al final de la lista.

.
De lo anterior, consideremos:

  1. Gestionar la configuraci贸n de Playwright para pre establecer la ruta base:

    export default defineConfig({
    	// ...
    	use: {
    		// ...
    	  baseURL: "https://demo.playwright.dev",
    		// ...
        },
    	// ...
    })
    
  2. Definir los hooks de ciclo de nuestro pool de pruebas:

    import { test, expect, type Page } from '@playwright/test'
    
    test.beforeEach(async ({ page }) => {
      await page.goto('/todomvc')
    })
    
  3. Establecer o requerir alg煤n(os) mock(s) para evaluar nuestros casos:

    import { test, expect, type Page } from '@playwright/test'
    import todoItems from './mocks/todoItems.mock.ts'
    
    test.beforeEach(async ({ page }) => {
      await page.goto('/todomvc')
    })
    
    export default [
    	'Clean the house',
    	'Feed the dog'
    ]
    
  4. Agrupar y definir nuestros casos de pruebas

    import { test, expect } from '@playwright/test'
    import todoItems from './mocks/todoItems.mock.ts'
    
    test.beforeEach(async ({ page }) => {
      await page.goto('/todomvc')
    })
    
    test.describe('TODO app', () => {
    	test('should be able to add a new item', async ({ page }) => {
    		// Input activity
    		// Validate text item
    	})
    	test('should append the last items added to the bottom of the list', async ({ page }) => {
    		// Input activity
    		// Validate text item
    	})
    })
    
  5. Completando los casos de pruebas

    import { test, expect, type Page } from '@playwright/test'
    import todoItems from './mocks/todoItems.mock.ts'
    
    test.beforeEach(async ({ page }) => {
        await page.goto('/todomvc')
    });
    
    test.describe('TODO app', () => {
        test('should be able to add a new item', async ({ page }) => {
            const newTodo = page.getByPlaceholder('What needs to be done?')
            await newTodo.fill(todoItems[0])
            await newTodo.press('Enter')
            await expect(page.getByTestId('todo-title')).toHaveText(todoItems[0])
        })
        test('should append the last items added to the bottom of the list', async ({
            page,
        }) => {
            const newTodo = page.getByPlaceholder('What needs to be done?')
            await newTodo.fill(todoItems[0])
            await newTodo.press('Enter')
            await newTodo.fill(todoItems[1])
            await newTodo.press('Enter')
            await expect(page.getByTestId('todo-item').nth(1)).toHaveText(todoItems[1])
        });
    });
    

Cuando trabajamos como Automation Tester uno de los problemas mas frecuentes que nos enfrentamos es lidiar con los selectores. Una de las recomendaciones que siempre podemos llevar a nuestro equipo de desarrollo es que se generen unos selectores unicos para testing, muy parecidos a los selectores por id. Entonces al trabajar con selectores unicos vamos a tener unos tests mucho mas robustos y podriamos evitar los flaky tests.

tambien me funciono con lo siguientes: //a\[normalize-space()='UITAP'] .navbar-brand "UITAP" $(".navbar-brand")

Nice!