Home > Enterprise >  Cypress not picking up html elements
Cypress not picking up html elements

Time:01-19

I'm trying to get a handle on a simple html <p> tag using the data-cy attribute:

<p data-cy="register">Register</p>

First I mount the component:

 it('mounts', () => {
        cy.mount(AccountDialogComponent, {
            imports: [ 
                HttpClientTestingModule, 
                ReactiveFormsModule,
                AngularMaterialModule,
                BrowserAnimationsModule
            ],
            declarations: [ AccountDialogComponent ],
            providers: [{provide: AccountService, useValue: accountService}]
        })
    });

The test I am running for this as follows:

it("text should be 'Register' when user is registering", () => {
    cy.get('[data-cy="register"]').should('have.text', 'Register');
});

The test keeps returning a failure:

assertexpected [data-cy="register"] to have text Register, but the text was ''

After another few seconds, it then returns an Assertion Error:

Timed out retrying after 4000ms: Expected to find element: [data-cy="register"], but never found it.

I can't understand why this isn't working?

I am new to Cypress and this is the first test I am dong since installing Cypress in my Angular app.

CodePudding user response:

I had same problem, this Angular - adding Cypress data-cy attribute sorted it out.

The gist is the Angular framework would not pass on data-cy without it's particular binding,

<p [attr.data-cy]="register">Register</p>

Now, test code will find your element.

BTW Component testing is ok if mount() ok, then it's same syntax for test assertions.

CodePudding user response:

Ok so it seems I was just forgetting that I need to mount the component before each test:

  beforeEach(async () => {
        cy.mount(AccountDialogComponent, {
            imports: [ 
                HttpClientTestingModule, 
                ReactiveFormsModule,
                AngularMaterialModule,
                BrowserAnimationsModule
            ],
            declarations: [ AccountDialogComponent ],
            providers: [{provide: AccountService, useValue: accountService}]
        })
    });
  • Related