Pruebas aisladas al componente
Clase 9 de 23 • Curso de Angular: Unit Testing para Componentes
Contenido del curso
Clase 9 de 23 • Curso de Angular: Unit Testing para Componentes
Contenido del curso
Jean Pool Zambrano Hernandez
Cesar Elías Armendariz Ruano
Carlos Alejandro Hernández Mejía
Franklin Gil
Si están usando Angular 17, deben crear el componente Host de la siguiente manera: @Component({ standalone: true, imports: [PersonComponent], template: `<app-person [person]="person" (onSelected)="onSelected($event)"></app-person>`})export class HostComponent { person = new Person('Santiago', 'Molina', 13, 40, 1.5); selectedPerson: Person | undefined;
onSelected(person: Person) { this.selectedPerson = person; }}
Esto es muy util cuando el componente tiene varios inputs y outputs por lo que estos componentes tienen ese comportamiento necesitan un padre para comprobar que este componente cumple con su función
person.component.spec.ts
fdescribe('PersonComponent from HostComponent', () => { let component: HostComponent; let fixture: ComponentFixture<HostComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ HostComponent, PersonComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(HostComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display person name', () => { // Arrange const expectName = component.person.name; const h3De = fixture.debugElement.query(By.css('app-person h3')); const h3El = h3De.nativeElement; // Act fixture.detectChanges(); // Assert expect(h3El.textContent).toContain(expectName); }); it('should raise selected event when do click', () => { // Arrange const btnDe = fixture.debugElement.query(By.css('app-person .btn-choose')); // Act btnDe.triggerEventHandler('click', null); fixture.detectChanges(); // Assert expect(component.selectedPerson).toEqual(component.person); }) })
Pruebas aisladas al componente
💡 Las pruebas aisladas entre componentes son pruebas que se realizan sobre un componente sin tener en cuenta sus dependencias o componentes hijos.
Normalmente, los componentes que poseen varios @Inputs (u @Outputs) se usan cómo hijos de otros componentes más grandes. En estos casos, es necesario ejecutar pruebas aisladas para verificar el comportamiento y la lógica del componente en sí, sin tener en cuenta cómo interactúa con otros componentes o servicios.
Para hacer pruebas aisladas, puedes seguir los siguientes pasos:
Definir un HostComponent que instancie a tu componente hijo:
@Component({ template: ` <app-child [input]="value" (onEvent)="onEventHandler($event)"> </app-child> `, }) export class HostComponent { value = 'myValue'; onEventHandler(value: string): void { // do something with the value } }
Defina un conjunto de pruebas aisladas para HostComponent y configure el entorno de pruebas para el mismo.
describe('ChildComponent from HostComponent', () => { let hostComponent: HostComponent; let fixture: ComponentFixture<HostComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [HostComponent, ChildComponent], }).compileComponents(); fixture = TestBed.createComponent(HostComponent); hostComponent = fixture.componentInstance; fixture.detectChanges(); }); it('should create a HostComponent', () => { expect(hostComponent).toBeTruthy(); }); // Test for the next step });
Escriba su conjunto de pruebas para el componente hijo. Por ejemplo
describe('Tests for the Child Component', () => { let childDebugElement : DebugElement; beforeEach(() => { childDebugElement = fixture.debugElement.query(By.directive(ChildComponent)); }); it('should have a ChildComponent', () => { expect(childDebugElement.componentInstance).toBeTruthy(); }); it('should have a ChildComponent with the value as HostComponent', () => { expect(childDebugElement.componentInstance.input).toEqual(hostComponent.value); }); it('should emit an event when do click', () => { // Arrange const button: DebugElement = childDebugElement.query(By.css('button[name="buttonName"]')); const onChildEventSpy= spyOn(childDebugElement.componentInstance, 'onEvent').and.callThrough(); const onEventHandlerSpy= spyOn(hostComponent, 'onEventHandler').and.callThrough(); // Act button.triggerEventHandler('click', null); // Assert expect(onChildEventSpy).toHaveBeenCalled(); expect(onEventHandlerSpy).toHaveBeenCalled(); }); // Another test cases });
El objetivo de un HostComponente es probar los input y outputs de un componente chiquito. Aislarlo de la logica general del componente padre.