Angular TS中Jest Mock服务报错:getContractClosurePage不是函数
问题原因
你定义的fakeContractClosureService中,getContractClosurePage不是一个可调用的函数——你直接把它赋值成了一个Observable实例,而组件代码里是通过this._contractClosureService.getContractClosurePage(true)来调用函数获取Observable的,自然会抛出“不是函数”的错误。
修复方案
把getContractClosurePage改成函数形式,让它接收参数(可以忽略参数值,直接返回预设的Observable):
const fakeContractClosureService = { getContractClosurePage: (bruteForce?: boolean) => 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' } ] }), };
进阶优化(可选)
如果需要验证函数是否被正确调用,或者后续要动态修改返回值,可以用Jest的mock函数:
const fakeContractClosureService = { getContractClosurePage: jest.fn().mockReturnValue(of({ services: [/* 你的测试数据 */] })), };
之后在测试用例里可以添加断言:
// 验证函数是否被调用,且参数正确 expect(_contractClosureService.getContractClosurePage).toHaveBeenCalledWith(true);
额外验证
测试初始化后可以加一行断言,确认mock服务已正确注入:
expect(_contractClosureService.getContractClosurePage).toBeDefined();
内容的提问来源于stack exchange,提问作者Flávio Costa
相关产品推荐
相关产品推荐

