Skip to content

Angular Component Testing: ngOnChanges does not fire when using Class syntax #23591

Description

@Waterstraal

Current behavior

When using the Class syntax in a Cypress Component test, ngOnChanges does not fire.,

Desired behavior

ngOnChanges should always fire when an input property is set.

Test code to reproduce

Create a component which implements OnChanges and make it set a flag which we display in the template:

import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-simple',
  template: `<div data-cy="simple">Hi {{ name }}. ngOnChanges fired: {{ ngOnChangesFired }}</div>`,
})
export class SimpleComponent implements OnChanges {
  @Input() name: string | undefined;

  ngOnChangesFired = false;

  ngOnChanges(changes: SimpleChanges): void {
    this.ngOnChangesFired = true;
  }
}

Create a Cypress component test and assert the output:

import { SimpleComponent } from './simple.component';

describe(`${SimpleComponent.name}`, () => {

  // This succeeds
  it('should fire ngOnChanges when using template syntax', () => {
    cy.mount(`<app-simple [name]="name"></app-simple>`, {declarations: [SimpleComponent], componentProperties: {name: 'Henk'}});

    cy.get('[data-cy=simple]').should('have.text', 'Hi Henk. ngOnChanges fired: true');
  });

  // This fails
  it('should fire ngOnChanges when using class syntax', () => {
    cy.mount(SimpleComponent, {componentProperties: {name: 'Henk'}});

    cy.get('[data-cy=simple]').should('have.text', 'Hi Henk. ngOnChanges fired: true');
  });

})

The first test succeeds (template syntax), and the second test fails (class syntax).

Cypress Version

10.6.0

Node version

16.15.1

Operating System

Windows 10

Debug Logs

No response

Other

Angular 13.3.11

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

CTIssue related to component testing

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions