如何解决Angular:ngx 引导模式的单元测试用例覆盖率
我有以下代码,我正在尝试为其编写单元测试用例:
onLogon(event: any,resetPassword = false): void {
this.bsModalRef = this.modalService.show(
LoginComponent,Object.assign(
{},{
animated: true,keyboard: false,backdrop: true,ignoreBackdropClick: true
},{ class: 'login-modal-popup' }
)
);
this.bsModalRef.content.event.subscribe(data => {
const type = data.type;
this.bsModalRef.hide();
if (type === 'register') {
this.processRegister(false,true);
} else if (type === 'forgot') {
this.processForgotDetails();
}
});
}
因此,当我单击登录按钮时,将调用 OnLogon 方法,该方法显示模态弹出窗口。另外,我已经订阅了模态组件的事件。
以下是我写的测试用例:
it('should call processForgotDetails() method for the forgot event',async(inject([BsModalService],(modalService: BsModalService) => {
spyOn(component,'processForgotDetails');
component.onLogon();
component.bsModalRef.content.event.next({type: 'forgot'});
fixture.detectChanges();
expect(component.processForgotDetails).toHaveBeenCalled();
})));
我创建了 BsModalService 存根,如下所示:
const bsModalServiceStub = {
show: jasmine.createSpy('show').and.callFake(function () {
return {
content: {
event: new EventEmitter()
}
};
}),hide: jasmine.createSpy('hide').and.callThrough(),};
但是测试用例失败并出现错误“Expected spy processForgotDetails to have been called。”
有人可以帮助我做错的地方吗?我在 BsModalService 存根中使用事件的方式是否正确?
我正在尝试实现 onLogon() 方法的完整覆盖。
解决方法
检查订阅调用中的测试是否有效
it('should call processForgotDetails() method for the forgot event',async(inject([BsModalService],(modalService: BsModalService) => {
spyOn(component,'processForgotDetails');
component.onLogon();
this.bsModalRef.content.event.subscribe(() => {
expect(component.processForgotDetails).toHaveBeenCalled();
});
component.bsModalRef.content.event.next({type: 'forgot'});
})));
,
确保您已为 BsModalService
配置模块提供程序以返回模拟实现。
TestBed.configureTestingModule({
...
providers: [{ provide: BsModalService,useValue: bsModalServiceStub }]
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。