You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

缩小jest.SpyInstance类型以解决ESLint报错问题

解决Jest Mock jose.createRemoteJWKSet时ESLint的any类型问题

核心思路

利用TypeScript的类型工具提取createRemoteJWKSet的原生类型,替换掉jest.SpyInstance中的any,同时优化断言逻辑,既满足ESLint要求又保证类型安全。

具体改造代码

import * as jose from 'jose';
import testConstants from './test-constants';

// 提取原函数的类型定义
type CreateRemoteJWKSetFn = typeof jose.createRemoteJWKSet;

export const buildCreateRemoteJWKSetMock = (
  // 用具体类型替换any:返回值类型 + 参数元组类型
  createRemoteJWKSetMock: jest.SpyInstance<ReturnType<CreateRemoteJWKSetFn>, Parameters<CreateRemoteJWKSetFn>>
): void => {
  createRemoteJWKSetMock.mockImplementation(
    // 参数类型自动推断,无需手动声明
    (url) => 
      // 返回的函数类型自动匹配原函数规范
      async (protectedHeader, token) => {
        // 可选优化:用合法的测试密钥替代双重断言(更严谨)
        // const { publicKey } = await jose.generateKeyPair('ES256');
        // return publicKey;
        
        // 若必须使用现有常量,保留断言但明确类型转换路径
        return testConstants.empty as unknown as jose.KeyLike;
      }
  );
};

批量处理类似场景的通用方案

对于其他jest spy的类型问题,都可以套用这个模式:

  • 用typeof 目标函数获取原生函数类型
  • 用ReturnType<函数类型>和Parameters<函数类型>填充jest.SpyInstance的泛型参数
  • mockImplementation的参数和返回值会自动推断,无需手动硬编码类型,彻底避免any

额外类型安全优化

如果测试中需要多次使用Mock密钥,建议在测试常量中提前生成合法的KeyLike实例:

// test-constants.ts
import * as jose from 'jose';

export const testPublicKey = await jose.generateKeyPair('ES256').then(res => res.publicKey);

之后直接返回testPublicKey,完全去掉双重断言,进一步提升类型安全性。

内容的提问来源于stack exchange,提问作者onefootswill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 05:45:02