Angular编写subscribe成功场景单元测试出现类型报错如何解决
问题根因
- 类型不匹配:你当前mock的返回值是空数组
[],但authProvider.resendOTP方法声明的返回值是 GraphQL 标准的FetchResult<ResendOTPResponse>类型,二者结构完全不一致,触发了TS类型校验报错。 - 逻辑结构缺失:就算绕过类型校验,你的业务代码需要从返回值中读取
result.data.resendOtp.id、result.data.resendOtp.access_token两个字段,空数组完全没有对应层级的属性,运行时会直接抛出属性读取错误。
解决方案
第一步:构造符合要求的mock响应
按照业务代码依赖的字段结构,构造和接口类型匹配的返回值:
const mockRes = { data: { resendOtp: { id: 'mock-temp-id', // 自定义测试用的假id access_token: 'mock-temp-token' // 自定义测试用的假token } } }
如果TS校验依然严格报错,说明需要补全FetchResult的其他必填属性,补充对应字段即可:
import { FetchResult } from '@apollo/client/core'; // 有需要就导入对应类型 const mockRes: FetchResult<ResendOTPResponse> = { data: { resendOtp: { id: 'mock-temp-id', access_token: 'mock-temp-token' } }, errors: null, extensions: {} }
第二步:修正单元测试代码
同时建议修正用例名(原用例名是错误场景的命名,和成功场景不符),并且提前mock业务代码中调用的其他依赖方法,避免额外报错:
it('should update display status and trigger success tip when resend OTP succeeds', () => { // 构造mock响应 const mockRes = { data: { resendOtp: { id: 'mock-temp-id', access_token: 'mock-temp-token' } } }; // mock resendOTP返回值 spyOn(providerService, 'resendOTP').and.returnValue(of(mockRes)); // mock其他依赖方法,避免未定义报错 spyOn(component.messageBoxService, 'showSuccess'); spyOn(component, 'startTimer'); // 触发方法 component.resendOTP(); // 断言结果 expect(component.tempId).toBe('mock-temp-id'); expect(component.tempToken).toBe('mock-temp-token'); expect(component.showResend).toBeFalsy(); expect(component.showResendInfo).toBeTruthy(); expect(component.messageBoxService.showSuccess).toHaveBeenCalledWith('SMS has been sent', 2000); expect(component.startTimer).toHaveBeenCalled(); });
内容的提问来源于stack exchange,提问作者justTrustMe
相关产品推荐
相关产品推荐

