Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 374

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T10:18:08+00:00 2024-11-25T10:18:08+00:00

Typed E2E test IDs

  • 62k

tl;dr – Improving the DX when writing E2E tests by using typed test IDs.

  • Utilizing TypeScript to create typed test IDs
  • Sharing test IDs between the frontend and the test suite:
// app/page.tsx <h1 {...e2e.home_heading}>   Welcome </h1>  // tests/home.spec.ts const heading = page.getByTestId(e2e.home_heading.id); 
  • Full example

When writing E2E tests, it is common to use test IDs to select elements on the page. This is especially useful when the element does not have a unique selector or when the selector is likely to change. However, hardcoding test IDs in place can lead to errors and make the test suite harder to maintain. In this post, I will present a pattern that allows you to share test IDs between the frontend and the test suite, and how to utilize TypeScript to create typed test IDs.

We start with a project that was bootstrapped with npx create-next-app. For the E2E test we use Playwright and set it up as described in the testing guide provided by Next.js.

Getting started

We start by simplifying the bootstrapped Next.js project, so that we have a single page left:

// app/page.tsx export default function Home() {   return (     <main>       <h1>         Welcome       </h1>     </main>   ); } 
Enter fullscreen mode Exit fullscreen mode

and write a simple E2E test for it:

// tests/home.spec.ts import { test, expect } from '@playwright/test';  test('has heading', async ({ page }) => {   await page.goto('/');    const heading = page.locator('h1');    await expect(heading).toBeVisible(); }); 
Enter fullscreen mode Exit fullscreen mode

This test is straightforward and checks if the heading is visible. The selector ('h1') for the heading is as simple as it gets but in a real-world application it is likely that we need to select elements in a more reliable way.

We can start by adding a test ID to the heading:

// app/page.tsx <h1 data-testid="home_heading">   Welcome </h1> 
Enter fullscreen mode Exit fullscreen mode

and update the test to use the test ID:

// tests/home.spec.ts const heading = page.getByTestId('home_heading'); 
Enter fullscreen mode Exit fullscreen mode

This is a huge improvement. The structure of the page can change now without breaking the test.

A straight forward approach

We can take the previous approach a step further by sharing the test ID between the frontend and the test suite. For this we create a file e2e.ts and define a object containing the test IDs:

// utils/e2e.ts const e2e = {   homeHeading: 'home_heading', }; 
Enter fullscreen mode Exit fullscreen mode

and import the test IDs in the page and in the test:

// app/page.tsx import { e2e } from '../utils/e2e';  <h1 data-testid={e2e.homeHeading}>   Welcome </h1> 
Enter fullscreen mode Exit fullscreen mode

// tests/home.spec.ts import { e2e } from '../utils/e2e';  const heading = page.getByTestId(e2e.homeHeading); 
Enter fullscreen mode Exit fullscreen mode

This alone already improves the DX and the maintainability of the test suite as we now have a single source of truth for the test IDs. The only thing we would have to remember when using this approach is the name of the data attribute data-testid and it would be nice if this is not the case.

Typed test IDs

Instead of setting the data attribute directly we could also pass it by spreading a corresponding object, for instance:

const testId = { 'data-testid': 'home_heading' };  // app/page.tsx <h1 {...testId} >   Welcome </h1> 
Enter fullscreen mode Exit fullscreen mode

Now, extending on that idea we can improve our previously defined e2e object:

// utils/e2e.ts const dataAttribute = 'data-testid' as const; const attributes = ['home_heading'] as const;  class Attribute<T extends string> {   [dataAttribute]: T;    constructor(value: T) {     this[dataAttribute] = value;   }    get id() {     return this[dataAttribute];   } }  type Mapped<T extends string> = {   [K in T]: Attribute<K>; };  type E2EAttributes = Mapped<typeof attributes[number]>;  export const e2e = Object.fromEntries(   attributes.map((attribute) => [attribute, new Attribute(attribute)]), ) as E2EAttributes; 
Enter fullscreen mode Exit fullscreen mode

Breaking it down, we define a dataAttribute and an array of attributes in a single location. Each attribute is then mapped to an Attribute class which enables us to spread the test ID in a component and, at the same time, comfortably access the test ID in the test suite. With the use of this approach our final test setup looks like this:

// app/page.tsx import { e2e } from '../utils/e2e';  <h1 {...e2e.home_heading}>   Welcome </h1> 
Enter fullscreen mode Exit fullscreen mode

// tests/home.spec.ts import { e2e } from '../utils/e2e';  const heading = page.getByTestId(e2e.home_heading.id); 
Enter fullscreen mode Exit fullscreen mode

Noteworthy is that we can safely spread the Attribute object in the component since spread only copies enumerable own properties, this means the id getter will have no effect on the component.

playwrighttestingtypescriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.