在Angular中,我们可以使用TestBed
和ComponentFixture
来测试EventEmitter
的订阅回调函数是否被执行。以下是一个解决方法的示例代码:
EventEmitter
和一个触发事件的方法:import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-test',
template: `
`
})
export class TestComponent {
@Output() myEvent: EventEmitter = new EventEmitter();
emitEvent() {
this.myEvent.emit();
}
}
TestBed
和ComponentFixture
来测试EventEmitter
的订阅回调函数是否被执行:import { TestBed, ComponentFixture } from '@angular/core/testing';
import { TestComponent } from './test.component';
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TestComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should emit event when button is clicked', () => {
spyOn(component.myEvent, 'emit');
const button = fixture.nativeElement.querySelector('button');
button.click();
expect(component.myEvent.emit).toHaveBeenCalled();
});
});
在上述代码中,我们使用spyOn
来监视myEvent.emit
方法是否被调用。然后,通过选择器选择按钮,并模拟点击按钮,最后使用expect
断言myEvent.emit
方法是否已被调用。
这是一个基本的示例,你可以根据实际需求对代码进行修改和扩展。