Skip to content

findByRole not working properly after element is present in DOM #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rafaelss95 opened this issue Nov 5, 2020 · 5 comments
Closed

findByRole not working properly after element is present in DOM #159

rafaelss95 opened this issue Nov 5, 2020 · 5 comments

Comments

@rafaelss95
Copy link
Contributor

rafaelss95 commented Nov 5, 2020

I have a markup that some elements visibility depends on a condition. Something like this:

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-test',
  template: `
    <form [formGroup]="formGroup">
      <mat-form-field>
        <mat-label>Number</mat-label>
        <input matInput required formControlName="number" />
      </mat-form-field>

      <ng-container *ngIf="formGroup.get('number').valid">
        <mat-form-field>
          <mat-label>Holder</mat-label>
          <input matInput required formControlName="holder" />
        </mat-form-field>

        <mat-form-field>
          <mat-label>Expiry</mat-label>
          <input matInput required formControlName="expiry" />
        </mat-form-field>

        <mat-form-field>
          <mat-label>CVV</mat-label>
          <input matInput required formControlName="cvv" />
        </mat-form-field>
      </ng-container>
    </form>
  `,
})
export class TestComponent {
  readonly formGroup = this.formBuilder.group({
    number: ['', [Validators.required, Validators.minlength(16), ...otherValidators]],
    holder: ['', [Validators.required, Validators.minlength(5), ...otherValidators]],
    expiry: ['', [Validators.required, Validators.minlength(7), ...otherValidators]],
    cvv: ['', [Validators.required, Validators.minlength(3), ...otherValidators]],
  });

  constructor(private readonly formBuilder: FormBuilder) {}
}

//////// Test file

async function setup() {
  const { rerender } = await render(TestComponent);
  const numberHtmlElementRef = screen.getByRole('textbox', { name: /number/i });
  const holderHtmlElementRef = screen.findByRole('textbox', { name: /holder/i });
  const expiryHtmlElementRef = screen.findByRole('textbox', { name: /expiry/i });
  const cvvHtmlElementRef = screen.findByRole('textbox', { name: /cvv/i });

  return {
    numberHtmlElementRef,
    holderHtmlElementRef,
    expiryHtmlElementRef,
    cvvHtmlElementRef,
    rerender,
  } as const;
}

describe(TestComponent.name, () => {
  test('someDescription', async () => {
    const {
      numberHtmlElementRef,
      holderHtmlElementRef,
      expiryHtmlElementRef,
      cvvHtmlElementRef,
    } = await setup();

    await expect(holderHtmlElementRef).rejects.toThrow(/Unable to find/i); // ok
    await expect(expiryHtmlElementRef).rejects.toThrow(/Unable to find/i); // ok
    await expect(cvvHtmlElementRef).rejects.toThrow(/Unable to find/i); // ok
    await userEvent.type(numberHtmlElementRef, '5353107424870314');
    expect(numberHtmlElementRef).toBeValid(); // ok
    await expect(holderHtmlElementRef).resolves.toBeInTheDocument(); // fail
    await expect(expiryHtmlElementRef).resolves.toBeInTheDocument(); // fail
    await expect(cvvHtmlElementRef).resolves.toBeInTheDocument(); // fail

    // If I don't reuse the element, like this, it works (or using `queryBy`/`getBy`):
    await expect(screen.findByRole('textbox', { name: /holder/i })).resolves.toBeInTheDocument(); // ok
    screen.getByRole('textbox', { name: /holder/i }); // ok
  });
}

So, the fields holder, expiry and cvv are visible once number is valid, but the tests keep failing. I noticed that if I query it again, using getByRole(...) to check if it's present in document, it works, but shouldn't findByRole(...) works in this case?

@timdeschryver
Copy link
Member

timdeschryver commented Nov 5, 2020

findByRole should work, I think.
I think it has similar problems as you just fixed in #158
My guess is that you can make a similar change here

Do you want to create a Pull Request? 🙂

@rafaelss95
Copy link
Contributor Author

Hey Tim,

I made the modification as you pointed but that still makes the test fail. I'm supposing that's maybe a "limitation" of findBy*.

What I did for now is to use queryBy* when I'm certain that it doesn't exists and when I'm certain that the element exists, I use getBy*, but I'm not sure about this, because it seems like I'm writing more duplicating the queries(selectors).

@timdeschryver
Copy link
Member

timdeschryver commented Nov 6, 2020

It could be that I misread the original issue.

  • queryBy does return the element when it's there or null when it isn't in the DOM
  • getBy throws immediately when the element isn't there
  • findBy does also throw but it tries a few times to find the element (and invokes the change detection with every try)

My advice is to use findBy when you expect an element, and queryBy to verify an element isn't there.

What I do think is that you will have to re-query for the element, instead of using the reference:

- await expect(holderHtmlElementRef).resolves.toBeInTheDocument(); // fail
+ await expect(screen.findByRole('textbox', { name: /holder/i })).resolves.toBeInTheDocument(); 

This could be a bug on our side tho, I haven't tested this with another testing library variant.

I hope this helps.

@timdeschryver
Copy link
Member

I tried this with RTL and the behavior is the same.
This is also the intended behavior because we keep a reference, but we have to re-query the element as you've also have noticed.

To not repeat the query you can wrap it inside a factory method:

const holderHtmlElementRef = () => screen.findByRole('textbox', { name: /holder/i });

await expect(holderHtmlElementRef()).rejects.toThrow(/Unable to find/i); 
await userEvent.type(numberHtmlElementRef, '5353107424870314');
await expect(holderHtmlElementRef()).resolves.toBeInTheDocument();

RTL reproduction

@rafaelss95
Copy link
Contributor Author

I tried this with RTL and the behavior is the same.
This is also the intended behavior because we keep a reference, but we have to re-query the element as you've also have noticed.

To not repeat the query you can wrap it inside a factory method:

const holderHtmlElementRef = () => screen.findByRole('textbox', { name: /holder/i });

await expect(holderHtmlElementRef()).rejects.toThrow(/Unable to find/i); 
await userEvent.type(numberHtmlElementRef, '5353107424870314');
await expect(holderHtmlElementRef()).resolves.toBeInTheDocument();

RTL reproduction

Thanks for the explanation :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants