primeNg ConfirmationService的Angular单元测试



我不知道如何在这个函数中测试accept和reject函数:

confirmReplan(event: any) {
this.confirmationService.confirm({
target: event.target,
key: 'replan',
message: 'lorem',
icon: 'pi pi-exclamation-triangle',
accept: () => {
this.messageService.add(/** **/);
this.replanRequest();
this.displayReplan = false;
},
reject: (type: any) => {
this.rejectMessage(type);
}
});
}
看着类似的问题,我尝试了很多解决方案。一个似乎对其他人有用的是这样的风格:
let component: RequestsTableComponent;
let fixture: ComponentFixture<RequestsTableComponent>;
let confirmationServiceSpy: ConfirmationService;
let requestServiceSpy: RequestApiService;
let messageServiceSpy: MessageService;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [RequestsTableComponent],
imports: [HttpClientTestingModule],
providers: [MessageService, RequestApiService, ConfirmationService]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RequestsTableComponent);
component = fixture.componentInstance;
fixture.detectChanges();
messageServiceSpy = TestBed.inject(MessageService);
requestServiceSpy = TestBed.inject(RequestApiService);
confirmationServiceSpy = TestBed.inject(ConfirmationService);
});
it('/**/', async() => {
spyOn(confirmationServiceSpy, 'confirm').and.callFake((confirmation: any) => {return confirmation.accept()});
component.confirmReplan({ target: undefined });
expect(confirmationServiceSpy.confirm).toHaveBeenCalled();
});

但是间谍从来没有被调用过。

jasmine coverage reporter的代码覆盖率报告

一种方法是对参数有一个句柄并手动调用acceptreject

it('/**/', async() => {
// associate this spy to a variable so we have a handle on it later
const confirmSpy = spyOn(confirmationServiceSpy, 'confirm');
component.confirmReplan({ target: undefined });
// get a handle on the most recent argument to this spy
const arg = confirmSpy.calls.mostRecent().args[0];
// call accept
arg.accept();
// call reject if you like
arg.reject();
expect(component.displayReplan).toBeFalse();
// now they should be covered
});

最新更新