Playwright Selector for Radio Button with same data-testid in ReactJs

Viewed 23

I need to test out a flow with PlayWright, where i need to change the checked radio button. Default "Myself" is selected, and needs to be changed to "Someone else". I normally use the data-testid to check it, but the issue is both of it has the same data-testid.

This is the html code,

<div class="flex justify-center">
   <div>
      <div class="mt-2">
         <div class="flex items-center flex-wrap -mt-2">
            <div class="mt-2 mr-8">
               <div class="flex items-center"><span class="pretty p-default p-round outline p-thick mr-0 "><input name="receiverType" type="radio" data-testid="value-card-receiver-type-radio-button" aria-label="Myself" value="myself" checked=""><span class="state p-primary-o"><span class="pretty-label">Myself</span></span></span></div>
            </div>
            <div class="mt-2 mr-8">
               <div class="flex items-center"><span class="pretty p-default p-round outline p-thick mr-0 "><input name="receiverType" type="radio" data-testid="value-card-receiver-type-radio-button" aria-label="Someone else" value="someoneElse"><span class="state p-primary-o"><span class="pretty-label">Someone else</span></span></span></div>
            </div>
         </div>
      </div>
   </div>
</div>

This is my PlayWright code,

export class MValueCardReceiverModalModel {
  private readonly page: Page;
  private readonly doneButton: Locator;
  private readonly backButton: Locator;
  private readonly someoneElseButton: Locator;

  constructor(page: Page) {
    this.page = page;
    this.doneButton = page.locator(
      "data-testid=modal >> data-testid=value-card-receiver-modal-done-button >> visible=true"
    );
    this.backButton = page.locator(
      "data-testid=modal >> data-testid=value-card-receiver-modal-back-button >> visible=true"
    );
    this.someoneElseButton = page.locator(
      "data-testid=modal >> data-testid=value-card-receiver-type-radio-button >> visible=true"
    );
  }

  async isAt(): Promise<void> {
    await expect(this.doneButton).toBeVisible();
    await expect(this.backButton).toBeVisible();
  }

  async selectForSomeoneElseButton(): Promise<void> {
    await this.someoneElseButton.check();
  }

  async clickDone(): Promise<void> {
    await this.doneButton.click();
  }
}

Here, when running the test, I am getting a issue in the selectForSomeoneElseButton().

Can someone tell what am I doing wrong in the selector.

1 Answers

I figured out the answer. Playwright throws error when two things have the same data-testid. Here both my radio buttons have the same testid. I fixed it by having seperate testid

Related