[英]@Output() EventEmitter does not emit when testing
我有以下代码
it('should emit Sound on save', () => {
spyOn(component, 'getBase64').and.returnValue(Promise.resolve({
then(onFulfill, onReject) { onFulfill('fulfilled!'); }
}));
spyOn(component, 'saveRecordedData').and.callThrough();
spyOn(component.recorded, 'emit');
component.isRecording = false;
component.blobUrl = {data: 'somedata'};
fixture.detectChanges();
saveBtn = fixture.debugElement.query(By.css('.fa-send')).triggerEventHandler('click', null);
fixture.detectChanges();
expect(component.saveRecordedData).toHaveBeenCalled();
expect(component.getBase64).toHaveBeenCalledTimes(1);
expect(component.recorded.emit).toHaveBeenCalled();
});
哪些测试以下代码
saveRecordedData() {
this.getBase64(this.blob).then((s: string) => {
const sound: Sound = {base64: s, mimeType: this.mimeType};
this.recorded.emit(sound);
});
}
问题是在测试中我得到错误: SoundRecorderComponent > should emit Sound on save
更新:如果我写期望如下
expect(component.saveRecordedData).toHaveBeenCalled();
expect(component.getBase64).toHaveBeenCalledTimes(1);
component.recorded.emit({base64: 's', mimeType: 'a'});
expect(component.recorded.emit).toHaveBeenCalled();
测试通过:):所以我假设 eventemitter 有效?
我相信this.recorded.emit(sound);
不叫。
为什么是this.recorded.emit(sound);
不叫?
解决了
此代码有效
it('should emit Sound on save', async () => {
spyOn(component, 'getBase64').and.returnValue(Promise.resolve({
then(onFulfill, onReject) { onFulfill('fulfilled!'); }
}));
spyOn(component, 'saveRecordedData').and.callThrough();
spyOn(component.recorded, 'emit');
component.isRecording = false;
component.blobUrl = {data: 'somedata'};
fixture.detectChanges();
saveBtn = fixture.debugElement.query(By.css('.fa-send')).triggerEventHandler('click', null);
fixture.detectChanges();
fixture.whenStable().then(res => {
expect(component.saveRecordedData).toHaveBeenCalled();
expect(component.getBase64).toHaveBeenCalledTimes(1);
expect(component.recorded.emit).toHaveBeenCalled();
});
});
注意:添加了async
和fixture.whenStable()
它可能会发生,因为 Promise 会为您的代码带来异步性,并且在 promise.then 回调之前调用断言。 您可以做的最简单的事情是返回可调用的 obj,而不是 promise。
spyOn(component, 'getBase64').and.returnValue({
then(onFulfill, onReject) { onFulfill('fulfilled!'); }
});
我在这里删除Promise.resolve
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.