不调用角度单元测试中的事件发射器



给定此组件...

export class MyComponent {
@Output() onActivateEditMode = new EventEmitter<boolean>();
constructor() {}
emitActivateEditMode(flag: boolean) {
this.onActivateEditMode.emit(flag);
}

。和这个模板...

<a (click)="emitActivateEditMode(true)" data-test-start-edit-project-btn>Edit</a>

。则此测试失败:

describe('MyComponent', () => {
... (TestBed imports etc)
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
spyOn(component, 'emitActivateEditMode');
fixture.detectChanges();
});
it('should activate editmode on click', () => {
const onActivateEditModeSpy = jest.spyOn(
component.onActivateEditMode,
'emit'
);
const startEditProjectBtn = fixture.debugElement.nativeElement.querySelector(
'[data-test-start-edit-project-btn]'
);
startEditProjectBtn.dispatchEvent(new Event('click')); // startEditProjectBtn.click() doesn't change the result, too
fixture.detectChanges();
expect(component.onActivateEditMode.emit).toHaveBeenCalledWith(true);
// expect(onActivateEditModeSpy).toHaveBeenCalledWith(true) ... doesn't change the result, too
});
});

测试输出为:

Expected: true
Number of calls: 0

该功能在浏览器中工作,但此测试设置中的某些内容是错误的。

我假设你同时使用Jasmine和Jest。问题是,当你监视函数(spyOn(时,你基本上只是在监视函数进行调用,实现细节就会消失。要使实施细节更加巧妙,您可以spyOn(component, 'emitActivateEditMode').and.callThrough();但我认为对您来说,这是不需要的。

describe('MyComponent', () => {
... (TestBed imports etc)
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
// remove the mock/spyOn to the function emitActivateEditMode
fixture.detectChanges();
});
it('should activate editmode on click', () => {
// spy on emit calls on onActivatedEditMode
const emitSpy = spyOn(component.onActivateEditMode, 'emit');
const startEditProjectBtn = fixture.debugElement.nativeElement.querySelector(
'[data-test-start-edit-project-btn]'
);
startEditProjectBtn.click();
fixture.detectChanges(); // fixture.detectChanges is not needed here, only if you want to see the update in the HTML.
expect(emitSpy).toHaveBeenCalledWith(true);
});

相关内容

  • 没有找到相关文章

最新更新