Reputation: 16664
I am trying to test a simple click event from a simple button component. With karma + jasmine, it is very straight forward, but I do not get it with jest.
Here is the button component I want to test:
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
@Component({
selector: 'ui-button',
styleUrls: ['./button.component.scss'],
templateUrl: './button.component.html',
})
export class ButtonComponent implements OnInit {
@Output() public click = new EventEmitter<void>();
constructor() {}
public ngOnInit() {}
}
<button type="button" class="btn btn-primary" click="click.emit($event)">
<ng-content></ng-content>
</button>
Now I want to test, if the EventEmitter is firing, when I click the button:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ButtonComponent } from './button.component';
describe('ButtonComponent', () => {
let component: ButtonComponent;
let fixture: ComponentFixture<ButtonComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ButtonComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ButtonComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should fire a click event', (done) => {
component.click.subscribe((event: any) => {
expect(event).toBeDefined();
done();
});
const htmlButton: HTMLButtonElement = fixture.nativeElement.querySelector('button');
htmlButton.click();
fixture.detectChanges();
});
});
Test fails, because the event is never firing as you can see in my log output:
FAIL libs/ui/src/lib/button/button.component.spec.ts (9.668s)
● ButtonComponent › should fire a click event
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:
31 | });
32 |
> 33 | it('should fire a click event', (done) => {
| ^
34 | component.click.subscribe((event: any) => {
35 | expect(event).toBeTruthy();
36 | done();
at new Spec (../../node_modules/jest-jasmine2/build/jasmine/Spec.js:116:22)
at env.(anonymous function) (../../node_modules/jest-preset-angular/zone-patch/index.js:84:27)
at src/lib/button/button.component.spec.ts:33:3
at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (../../node_modules/zone.js/dist/zone.js:391:26)
at Zone.Object.<anonymous>.Zone.run (../../node_modules/zone.js/dist/zone.js:150:43)
at Suite.<anonymous> (../../node_modules/jest-preset-angular/zone-patch/index.js:40:21)
at env.(anonymous function) (../../node_modules/jest-preset-angular/zone-patch/index.js:69:27)
at Object.<anonymous> (src/lib/button/button.component.spec.ts:4:1)
What do I need to change, so that my event is firing?
Upvotes: 1
Views: 2357
Reputation: 2431
I don't understand how it could works with karma/jasmine ?
I think that's because of your usage of event emitter :
<button type="button" class="btn btn-primary" (click)="click.emit($event)">
<ng-content></ng-content>
</button>
Otherwise your test seems to be good
Upvotes: 1