我正在用一个按钮测试一个非常简单的组件。当单击按钮时,它会发出一个(@output)
事件,然后调用父级的回调(chatMessageFeedbackHandler
)。没什么不寻常的。
但由于某些原因,下面的测试不起作用。我只是在测试单击子对象的chatMessageFeedbackHandler
时是否调用了父对象的button#test1
。
注意:如果您注释了以下任一测试,则会成功运行:
测试:
import {async, ComponentFixture, fakeAsync, flushMicrotasks, TestBed, tick} from '@angular/core/testing';
import {Component, DebugElement} from "@angular/core";
import {AppComponent} from './app.component';
import {By} from '@angular/platform-browser';
function createHostComponent(): ComponentFixture<HostComponent> {
const fixture = TestBed.createComponent(HostComponent);
fixture.detectChanges();
return fixture as ComponentFixture<HostComponent>;
}
fdescribe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<HostComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HostComponent, AppComponent],
})
// .compileComponents();
}));
beforeEach(() => {
// fixture = TestBed.createComponent(ChatFeedbackComponent);
fixture = createHostComponent();
});
fit('should emit chatMessageFeedback$ true when clicked on like button', fakeAsync(() => {
const appComponent = fixture.debugElement.query(By.directive(AppComponent)) as DebugElement;
// spyOn(appComponent.componentInstance,'chatFeedbackClicked');//LINE: parent 1.1
spyOn(fixture.componentInstance,'outputHandler'); //LINE: child 1.1
fixture.debugElement.nativeElement.querySelector('#test1').click();
tick(500);
flushMicrotasks();
fixture.detectChanges();
// expect(appComponent.componentInstance.chatFeedbackClicked).toHaveBeenCalled();//LINE: parent 1.2
expect(fixture.componentInstance.outputHandler).toHaveBeenCalledWith(true);//LINE: child 1.2
}));
});
@Component({selector: 'host-for-test', template: `
<app-root (chatMessageFeedback$)="outputHandler($event)"></app-root>
`})
class HostComponent {
outputHandler(data) {
alert();
}
}
子组件:
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
@Component({
selector: 'app-root',
template: `
<button id="test1" (click)="chatFeedbackClicked(true)">Test</button>
`,
})
export class AppComponent {
@Output() chatMessageFeedback$ = new EventEmitter();
chatFeedbackClicked(isFeedbackPositive: boolean) {
this.chatMessageFeedback$.emit(isFeedbackPositive);
}
}
https://stackoverflow.com/questions/56373420
复制相似问题