如何Mock jwtDecode?遇到类型错误‘"default"不能赋值给never’
问题解决:jwtDecode测试报错 "Argument of type '"default"' is not assignable to parameter of type 'never'"
问题根源
你在测试里尝试 spy jwtDecode.default,但实际项目中jwtDecode是默认导出的函数,并非带有default属性的对象,这种spy方式不符合TypeScript类型定义,因此触发报错。
修复方案
方案1:调整spy写法(适配Angular测试)
如果组件中是默认导入jwtDecode(import jwtDecode from 'jwt-decode'),直接spy函数本身即可,无需访问default属性:
it('should test labId with more than 4 chars', inject([OauthService], (oauthService: OauthService) => { const parsedToken = { principal: '1234lab' }; // 直接spy jwtDecode函数,转换类型避免TS报错 const jwtDecodeSpy = spyOn(jwtDecode as unknown as {(): any}, '__proto__').and.returnValue(parsedToken); component.setUpOAuth(); // 传入符合AccessToken类型的对象,需包含toString方法 oauthService.onLoggedIn.next({ toString: () => 'fake-jwt-token' }); expect(LabIdManager.labId).toBe('1234lab'); }));
方案2:Jest模块Mock(推荐)
如果使用Jest测试框架,直接mock整个jwt-decode模块更简洁,彻底规避类型问题:
// 在测试文件顶部mock模块 jest.mock('jwt-decode', () => jest.fn(() => ({ principal: '1234lab' }))); it('should test labId with more than 4 chars', inject([OauthService], (oauthService: OauthService) => { component.setUpOAuth(); // 传入符合AccessToken类型的对象 oauthService.onLoggedIn.next({ toString: () => 'any-token-string' }); expect(LabIdManager.labId).toBe('1234lab'); }));
额外注意点
组件中调用jwtDecode(token.toString()),因此测试时onLoggedIn.next()必须传入符合AccessToken类型的对象,至少要包含toString()方法,否则会触发其他报错。
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

