¿Alguna forma de probar EventEmitter en Angular2?
Tengo un componente que usa un EventEmitter y el EventEmitter se usa cuando se hace clic en alguien en la página. ¿Hay alguna forma de que pueda observar el EventEmitter durante una prueba unitaria y usar TestComponentBuilder para hacer clic en el elemento que desencadena el EventEmitter?siguiente método () y ver lo que se envió?
3 answers
Su prueba podría ser:
it('should emit on click', inject([], () => {
tcb.createAsync(MyComponent)
.then((fixture) => {
// spy on event emitter
let component = fixture.componentInstance;
spyOn(component.myEventEmitter, 'emit');
// trigger the click
let nativeElement = fixture.nativeElement;
let button = nativeElement.querySelector('button');
button.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(component.myEventEmitter.emit).toHaveBeenCalledWith('hello');
});
}));
Cuando su componente es:
@Component({ ... })
class MyComponent {
@Output myEventEmitter = new EventEmitter();
buttonClick() {
this.myEventEmitter.emit('hello');
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-11 20:48:44
Supongamos que tiene un método llamado buttonClick()
que dispara un emisor de eventos llamado eventEmitter
, puede suscribirse al evento y luego llamar al método para ver si el evento se dispara, y llamar a la devolución de llamada done()
cuando lo haga...
@Component({ ... })
class MyComponent {
@Output() eventEmitter = new EventEmitter();
buttonClick() {
this.eventEmitter.emit('bar');
}
}
Y luego en la prueba...
it('should emit on click', (done) => {
component.eventEmitter.subscribe(foo => {
expect(foo).toEqual('bar');
done();
});
component.buttonClick();
});
Alternativamente, puedes usar un espía, depende de tu estilo. Así es como usarías un espía fácilmente para ver si emit
está siendo disparado...
it('should emit on click', () => {
spyOn(component.eventEmitter, 'emit');
component.buttonClick();
expect(component.eventEmitter.emit).toHaveBeenCalled();
expect(component.eventEmitter.emit).toHaveBeenCalledWith('bar');
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-05 12:56:03
Puede suscribirse al emisor o vincularse a él, si es un @Output()
, en la plantilla padre y verificar en el componente padre si el enlace se actualizó.
También puede enviar un evento de clic y luego la suscripción debería activarse.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-10 15:40:59