错误即使在测试方法中监视了方法,也应调用预期的Spy



我正在编写一个jasmine测试来测试angular中的方法调用。我正在测试调用方法this.calculateRemainingDaysLeftin getOutstandingAgreements方法。我目前收到错误

Expected spy calculateRemainingDaysLeft to have been called.

我在测试中尝试了以下内容,但没有一个能帮助我解决问题

expect(component.calculateRemainingDaysLeft).toHaveBeenCalled();
//expect(mockAgreementsService.getOutstandingAgreements).toHaveBeenCalled();

组件

public getOutstandingAgreements(Id: number) {
this.agreementsService.getOutstandingAgreements(Id).subscribe((data: AgreementsModel[]) => {
this.myData = data;
if (this.myData) {
this.agreementData = this.myData[0].data;
this.agreementLength = this.myData.length;
this.calculateRemainingDaysLeft(0);
}
});
}

测试文件

describe('AgreementComponent', () => {
let component: AgreementComponent;
let fixture: ComponentFixture<AgreementComponent>;
let  mockAgreementsService: AgreementsService;

const mockAgreementsService: any = {
getOutstandingAgreements(): Observable<AgreementsModel[]> {
return Observable.of([]);
},
updateAgreement: () => Promise.resolve([])
};
configureTestSuite(() => {
TestBed.configureTestingModule({
imports: [SharedModule, FontAwesomeModule],
declarations: [AgreementComponent, CustomScrollDirective],
providers: [{ provide: UserService, useValue: mockUserService },
{ provide: AgreementsService, useValue: mockAgreementsService }]
});
});  


fit('should not return data when  getOutstandingAgreements is called', () => {
const response: AgreementsModel[] = [];
let outStandingAgreementSpy: jasmine.Spy;
let outStandingAgreementServiceSpy: jasmine.Spy;

setupComponent();
outStandingAgreementSpy = spyOn(component, 'getOutstandingAgreements').and.callThrough();
outStandingAgreementServiceSpy = spyOn(mockAgreementsService, 'getOutstandingAgreements').and.returnValue( null);
spyOn(component, 'calculateRemainingDaysLeft').and.callFake(function() {});
//spyOn(component, 'calculateRemainingDaysLeft').and.callThrough();
component.ngOnInit();
expect(outStandingAgreementSpy).toHaveBeenCalled();
expect(component.calculateRemainingDaysLeft).toHaveBeenCalled();
});

更改以下行:

outStandingAgreementServiceSpy = spyOn(mockAgreementsService, 'getOutstandingAgreements').and.returnValue( null)

至:

outStandingAgreementServiceSpy = spyOn(mockAgreementsService, 'getOutstandingAgreements').and.returnValue( Observable.of(''))

最新更新