Can't address imported Angular Component's Selector in Cypress Component Test

265 views Asked by At

I import an angular component from a library. It has the selector <imported-component-group>.

I place this component inside my local angular component.

When writing a cypress component test, I can't access this imported component by its component name, but only by a class name I assign to it.

This is how I place the imported component inside my local component:

<imported-component-group *ngIf="showImportedComponent(condition$) | async" class="importedComponentGroup">
   
   <imported-component>
   ...
   </imported-component>
   
   <imported-component>
   ...
   </imported-component>
   
</imported-component-group>

And from my component test, I try to address it like so:

cy.get('imported-component-group')

and so:

cy.get('<imported-component-group>')

Both approaches do not find my component, but it works, if I address it via the class instead:

cy.get('.importedComponentGroup')

The *ngIf condition should not be the problem, otherwise cy.get('.importedComponent') would not find it either. Also, this component exists only once within the HTML code.

Since I only created the class for the component test, I would like to get rid of it and directly address the component by its tag name.

It would be great if anybody has an idea about what I am missing here.

1

There are 1 answers

1
Lola Ichingbola On

To illustrate looking at DOM tags, have a look at the Cypress sample cypress-component-testing-apps /angular-standalone/. (Note I needed to install @angular-devkit/core which is missing in the package.json)

If you look at the spec app.component.cy.ts which is for AppComponent which contains/uses WelcomeComponent (running only the first test), the DOM looks like this:

enter image description here

which shows the WelcomeComponent with tag <app-welcome>, and I can select on that tag by adding this line to the test:

...
cy.get('app-welcome').should('contain', 'Welcome testuser')

But if I run the spec welcome.component.cy.ts (just the first test again), the DOM looks like this:

enter image description here

now there is no tag <app-welcome> available for Cypress to select on, it's just providing the raw HTML that the component template gives:

<div class="max-w-screen-sm p-12 mx-auto bg-gray-50 rounded-md shadow-lg">
    <h1 class="test-2xl">Welcome {{ username }}</h1>
    <app-button (onClick)="onLogout.emit()">Log Out</app-button>
</div>

I'm not sure how comparable this example is when using and external lib component, but you can check the DOM in your own test.

You can't go by the source template, you will need to inspect the DOM via devtools.