Bienvenida e Introducci贸n

1

驴Qu茅 son las pruebas unitarias?

2

驴Por qu茅 hacer pruebas unitarias?

Creando un framework de pruebas b谩sico

3

Mi primera prueba unitaria en JavaScript

4

Las funciones expect() y it()

5

Organizando el c贸digo para correr en la web

6

Organizando el c贸digo para correr utilizando nodejs

An谩lisis est谩tico de c贸digo

7

Herramientas de an谩lisis est谩tico de c贸digo

8

ESLint: Agregando alertas a nuestro c贸digo con ECMA Script

9

Herramientas de correcci贸n de estilo

10

Herramientas de tipado

Trabajando con Jasmine en el frontend

11

Profundizaci贸n en SpyOn: Comandos m谩s utilizados y c贸mo ponerlos a prueba

12

Configurar un ambiente de trabajo para trabajar con el framework jasmine

13

Configurar Jasmine utilizando Node.js

14

Primer set de pruebas con Jasmine

15

Diccionario Jasmine

Probando Nodejs apps con Jasmine

16

Introducci贸n al m贸dulo de testing del lado del servidor

17

Configurando el proyecto Jasmine utilizando npm

18

Agregando Plugins a Jasmine

19

Configurando nuestro reporter

20

Pruebas en el servidor: Verificando un status 200 en GET

21

Pruebas en el servidor: Probando el m茅todo GET y Reto con FindByID

22

Pruebas en el servidor: Probando el m茅todo POST (request to server)

23

Pruebas en el servidor: Probando el m茅todo POST (request to PDF)

Probando Angular apps con Jasmine

24

Tipos de pruebas

25

Pruebas en el frontend: Probando el componente principal (App)

26

Configurando los ciclos de vida

27

Creando las pruebas del formulario: Configuraci贸n

28

Creando las pruebas necesarias para un formulario. (Primeras pruebas)

29

Probando el caso de exito al guardar un elemento en el servidor.

30

Trabajando con event emitters

31

Testeando ngZone y navegaci贸n.

32

Configurando el TestBed de el componente PINs

33

Creando un espia sobre el objecto window

Pruebas de integraci贸n de Angular apps con Jasmine

34

Ejecutando funciones a trav茅s de eventos en el template

35

Probando la navegaci贸n

36

Probando servicios con HTTP

37

Completando las pruebas del servicio HTTP

38

Cierre del curso

A煤n no tienes acceso a esta clase

Crea una cuenta y contin煤a viendo este curso

Curso de Unit Testing para MEAN con Jasmine

Curso de Unit Testing para MEAN con Jasmine

Cristian Daniel Marquez Barrios

Cristian Daniel Marquez Barrios

Testeando ngZone y navegaci贸n.

31/38
Recursos

Aportes 10

Preguntas 0

Ordenar por:

驴Quieres ver m谩s aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesi贸n.

As铆 implement茅 los tests sobre el componente 鈥淎ction鈥

it('should openLink', () => {
    const event = new MouseEvent('click');
    const eventCall = spyOn(event, 'preventDefault').and.callFake(() => {});
    const dismiss = spyOn((<any>component).bottomSheetRef, 'dismiss');
    const resolveActionObserver = spyOn(
      (<any>component).pinsService,
      'resolveActionObserver'
    );
    component.openLink(event, '');
    expect(eventCall).toHaveBeenCalled();
    expect(dismiss).toHaveBeenCalled();
    expect(resolveActionObserver).toHaveBeenCalled();
  });
it("edit mode should be true", () => {
    const verifyEditMode = spyOn(component, "verifyEditMode").and.callThrough();

    fixture.ngZone.run(() => {
      (<any>component).router.navigate(['app/add']); 
      fixture.whenStable().then(() => {
        expect(component.editMode).toBe(true);
        expect(verifyEditMode).toHaveBeenCalled();
      });
    });
  });

Mi c贸digo completamente funcional:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ActionsComponent } from './actions.component';
import { MatBottomSheetRef } from '@angular/material';
import { PinsService } from '../pins/pins.service';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

class MatBottomSheetRefStub {
  dismiss() { }
}

class PinsServiceStub {
  resolveActionObserver(action) { }
}

fdescribe('ActionsComponent', () => {
  let component: ActionsComponent;
  let fixture: ComponentFixture<ActionsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ActionsComponent],
      providers: [
        { provide: MatBottomSheetRef, useClass: MatBottomSheetRefStub },
        { provide: PinsService, useClass: PinsServiceStub }
      ],
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ActionsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should execute openLink', () => {

    // se crea el evento
    const event = new MouseEvent('click');

    // se crean los espias de las funciones que queremos comprobar que fueron llamadas
    const eventSpy = spyOn(event, 'preventDefault').and.callFake(() => { });
    const bottomSheetRefSpy = spyOn((<any>component).bottomSheetRef, 'dismiss');
    const pinsServiceSpy = spyOn((<any>component).pinsService, 'resolveActionObserver');

    // la funcion que estamos probando, la espiamos sin modificar su comportamiento
    const openLink = spyOn(component, 'openLink').and.callThrough();


    // ejecutamos la funcion
    component.openLink(event, 'send');

    // comprobamos los resultados
    expect(openLink).toHaveBeenCalledWith(event, 'send');
    expect(eventSpy).toHaveBeenCalled();
    expect(bottomSheetRefSpy).toHaveBeenCalled();
    expect(pinsServiceSpy).toHaveBeenCalledWith('send');
  });
});

En versiones mas recientes de Angular al ejecutar fixture.whenStable().then() se debe invocar el it mediante un async o sino nuestra prueba nos arrojara un warn diciendo que no tiene ningun expect.

El codigo actualizado seria asi

it("should set the edit mode to false", async(() => {
	const verifyEditmode = spyOn(component, "verifyEditMode").and.callThrough();

	fixture.ngZone.run(() => {
		(<any>component).router.navigate(["/"]);

		fixture.whenStable().then(() => {
			expect(component.editMode).toBeFalsy();
			expect(verifyEditmode).toHaveBeenCalled();
		});
	});
}));

No me queda claro porque forzas la prueba. A caso no deberia correr y ya? Porque no te corren y tenes que forzarlo?

Configure asi para testear la ruta 鈥/app/add鈥

declarations: [LayoutComponent, FormComponent],
      providers: [{ provide: MatBottomSheet, useClass: MatBottomSheetStub }],
      imports: [RouterTestingModule.withRoutes([
        { path: '', component: LayoutComponent },
        {
          path: "app", component: LayoutComponent,
          children: [{ path: "add", component: FormComponent }]
        },
      ])],
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA]

Y agregue este import
import { FormComponent } from 鈥樷/form/form.component鈥;

Pero me da este error
Error: StaticInjectorError(DynamicTestModule)[FormComponent -> FormBuilder]:

Que me falta hacer?

import { async, ComponentFixture, TestBed } from "@angular/core/testing";

import { ActionsComponent } from "./actions.component";
import { MatBottomSheetRef } from "@angular/material";
import { PinsService } from "../pins/pins.service";
import { NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";

export class MatBottomSheetRefSTUB {
  dismiss() {}
}

export class PinsServiceSTUB {
  resolveActionObserver(action) {}
}

fdescribe("ActionsComponent", () => {
  let component: ActionsComponent;
  let fixture: ComponentFixture<ActionsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ActionsComponent],
      providers: [
        { provide: MatBottomSheetRef, useClass: MatBottomSheetRefSTUB },
        { provide: PinsService, useClass: PinsServiceSTUB },
      ],
      schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ActionsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it("should create", () => {
    expect(component).toBeTruthy();
  });

  it("preventDefault should be called", () => {
    const mouseEvent = new MouseEvent("click");
    const mouseEventSpy = spyOn(
      mouseEvent,
      "preventDefault"
    ).and.callFake(() => {});
    component.openLink(mouseEvent, "send");
    expect(mouseEventSpy).toHaveBeenCalled();
  });

  it("dismiss should be called", () => {
    const mouseEvent = new MouseEvent("click");
    spyOn(mouseEvent, "preventDefault").and.callFake(() => {});
    const bottomSheetRefSpy = spyOn((<any>component).bottomSheetRef, "dismiss");
    component.openLink(mouseEvent, "send");
    expect(bottomSheetRefSpy).toHaveBeenCalled();
  });

  it("dismiss should be called", () => {
    const mouseEvent = new MouseEvent("click");
    spyOn(mouseEvent, "preventDefault").and.callFake(() => {});
    const pinsServiceSpy = spyOn(
      (<any>component).pinsService,
      "resolveActionObserver"
    );
    component.openLink(mouseEvent, "send");
    expect(pinsServiceSpy).toHaveBeenCalled();
  });
});

Esto fue lo que hice 馃槄. Por cierto, el casting tambi茅n lo pueden hacer como (component as any).

class MatBottomSheetRefStub<T> {
  dismiss() {}
}

class PinsServiceStub {
  resolveActionObserver(action: string) {}
}

describe('ActionsComponent', () => {
  let component: ActionsComponent;
  let fixture: ComponentFixture<ActionsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ActionsComponent ],
      providers: [
        { provide: MatBottomSheetRef, useClass: MatBottomSheetRefStub },
        { provide: PinsService, useClass: PinsServiceStub }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ActionsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should open a link', () => {
    const event = new MouseEvent('click');
    const mouseEvent = spyOn(event, 'preventDefault');
    const dismiss = spyOn((component as any).bottomSheetRef, 'dismiss');
    const resolve = spyOn((component as any).pinsService, 'resolveActionOberver');
    component.openLink(event, 'ok');
    expect(mouseEvent).toHaveBeenCalled();
    expect(dismiss).toHaveBeenCalled();
    expect(resolve).toHaveBeenCalledWith('ok');
  });
});

Que es ese (<any>component) que pones??

import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import {
  async,
  ComponentFixture,
  TestBed,
  waitForAsync,
} from '@angular/core/testing';
import { MatBottomSheet } from '@angular/material/bottom-sheet';
import { RouterTestingModule } from '@angular/router/testing';
import { ActionsComponent } from '../actions/actions.component';

import { LayoutComponent } from './layout.component';

class MatBottomSheetStub {
  open() {}
}

fdescribe('LayoutComponent', () => {
  let component: LayoutComponent;
  let fixture: ComponentFixture<LayoutComponent>;

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [LayoutComponent],
        providers: [{ provide: MatBottomSheet, useClass: MatBottomSheetStub }],
        imports: [
          RouterTestingModule.withRoutes([
            { path: '', component: LayoutComponent },
            { path: 'app/add', component: LayoutComponent },
          ]),
        ],
        schemas: [NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA],
      }).compileComponents();
    })
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(LayoutComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('Should set the editMode to false', () => {
    const verifyEditMode = spyOn(component, 'verifyEditMode').and.callThrough();

    fixture.ngZone.run(() => {
      (<any>component).router.navigate(['/']);

      fixture.whenStable().then(() => {
        expect(component.editMode).toBeFalsy();
        expect(verifyEditMode).toHaveBeenCalled();
      });
    });
  });

  it('Should open', () => {
    const open = spyOn((<any>component).bottomSheet, 'open');

    component.openBottomSheet();

    expect(open).toHaveBeenCalledWith(ActionsComponent);
  });


  it('Should set the editMode to true', () => {
    const verifyEditMode = spyOn(component, 'verifyEditMode').and.callThrough();

    fixture.ngZone.run(() => {
      (<any>component).router.navigate(['app/add']);

      fixture.whenStable().then(() => {
        expect(component.editMode).toBeTruthy();
        expect(verifyEditMode).toHaveBeenCalled();
      });
    });
  });
});