【发布时间】:2019-11-28 10:44:02
【问题描述】:
我正在尝试从一个简单的按钮组件测试一个简单的点击事件。用因果报应+茉莉花,很直接,但玩笑我不明白。
这是我要测试的按钮组件:
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>
现在我想测试一下,当我点击按钮时,EventEmitter 是否正在触发:
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();
});
});
测试失败,因为正如您在我的日志输出中看到的那样,该事件永远不会触发:
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)
我需要更改哪些内容才能触发我的事件?
【问题讨论】:
标签: angular unit-testing jestjs