在 Angular 的测试中,我们可以使用 Output
装饰器来测试组件的输出属性。它允许我们模拟事件并检查事件是否触发并且输出属性是否正确设置。
例如,假设我们有一个名为 appComponent
的组件,它具有一个名为 myOutput
的输出属性。我们可以创建以下测试:
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AppComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should emit myOutput', () => {
spyOn(component.myOutput, 'emit');
component.someMethodThatTriggersMyOutput();
expect(component.myOutput.emit).toHaveBeenCalledWith('some value');
});
});
在这个测试中,我们首先使用 spyOn
从输出属性 myOutput
中创建一个模拟方法。然后,我们调用触发 myOutput
的方法,并使用 expect
断言 emit
方法已被调用并传入了正确的值。
通过这种方式,我们可以轻松地测试 Angular 组件的输出属性。