如何使用JEST(Angular Ts)模拟服务



我试图模拟一个简单的服务,它为我返回一个Observable。

这是我需要测试的组件

constructor(
private _contractClosureService: ContractClosureService,
private _contractClosureState: ContractClosureStateService,
private _router: Router
) {}
ngOnInit(): void {
this._contractClosureService
.getContractClosurePage(true)
.subscribe((response: any) => {
this.contractClosurePageResponse = response.services
.filter((x: any) => typeof x !== undefined)
.shift();
this.contractClosureInputUI = this.contractClosurePageResponse?.pages
.filter((x) => typeof x !== undefined)
.shift();
this._contractClosureState.setContractClosureInputUI(
this.contractClosureInputUI
);
});
}

这就是我的服务(ContractClosureService(

getContractClosurePage(
bruteForce?: boolean
): Observable<ServiceContractClosureResponseModel> {
this._loggerService.log(
NgxLoggerLevel.INFO,
'getting getContractClosurePage...',
`with bruteForce equals ${bruteForce}`
);
return this.executeQuery(
this._contractClosureQuery,
'contractClosure',
bruteForce
);
}

ContractClosureService:的提供者配置模块

TestBed.configureTestingModule({
imports: [
ApolloTestingModule,
RouterTestingModule.withRoutes([
{
path: CONTRACT_CLOSURE_ROUTES.LANDING_PAGE,
component: ContractClosureLandingPageComponent,
},
{
path: 'encerrar-contrato/' + CONTRACT_CLOSURE_ROUTES.MAIN,
component: ContractClosureComponent,
},
{
path: 'encerrar-contrato/' + CONTRACT_CLOSURE_ROUTES.FEEDBACK,
component: ContractClosureFeedbackComponent,
},
]),
UiCelescModule,
LoggerTestingModule
],
declarations: [ContractClosureLandingPageComponent],
providers: [
ContractClosureStateService,
// ContractClosureService,
{ provide: ContractClosureService, useValue: fakeContractClosureService },
{ provide: 'strapiPages', useValue: _strapiPages }
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents();
_controller = TestBed.inject(ApolloTestingController);
_contractClosureService = TestBed.inject(ContractClosureService);
_contractClosureStateService = TestBed.inject(ContractClosureStateService);
}));

最后是我的fakeService:

const fakeContractClosureService = {
getContractClosurePage: of({
services: [
{
mainTitle: 'Title test',
mainSubtitle: 'Subtitle test',
mainIcon: 'icon-test',
assetInfoTitle: 'Asset info title',
assetInfoSubtitle: 'Asset info subtitle',
readingTypeTitle: 'Reading type title',
readingTypeSubtitle: 'Reading type subtitle',
sendSectionTitle: 'Send section title',
sendSectionSubtitle: 'Send section subtitle'
}
]
}),
};

当我尝试cmd运行测试时,我遇到了一个笑话错误。TypeError:这个_contractClosureService.getContractClosurePage不是函数

我认为mock无法找到所提供的参考。

有人帮忙吗?

你差点就受够了,改一下:

const fakeContractClosureService = {
getContractClosurePage: of({

对此:

const fakeContractClosureService = {
getContractClosurePage: () => of({

因为CCD_ 1是函数而不是属性值。

最新更新