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

如何绕过对外类构造函数类型检测以测试验证代码?

如何用jestjs + ts-jest绕过类型检查编写输入验证的单元测试?

我有一个对外暴露的类,其中包含输入验证代码,用于该库被导入到不支持类型检查的JavaScript环境的场景。我正尝试为该验证代码编写单元测试。

// function-token.ts;

// ...

export default class FunctionToken extends Token {
  constructor(token: IFunctionToken) {
    if (token == null) {
      throw new Error('token must be specified');
    }
    
    // ...

  }
}

目前我尝试用jestjs编写验证代码的测试时,因类型检查而失败:

// function-token.spec.ts

import FunctionToken from 'function-token';

test('throws an error when token is nullish', function () {
  // Expected 1 arguments, but got 0 - An argument for 'token' was not provided
  expect(() => new FunctionToken()).toThrow();

  // Argument of [undefined|null] is not assignable to IFunctionToken
  expect(() => new FunctionToken(undefined)).toThrow();
  expect(() => new FunctionToken(null)).toThrow();
});

注:修改类本身的类型定义并不合理,因为该验证是专门针对无类型检查或强制的场景。


可行解决方案

方法1:使用类型断言绕过检查

通过unknown中转的类型断言,明确告知TypeScript我们要传入不符合定义的参数:

test('throws an error when token is nullish', function () {
  // 无参数场景:将构造函数转为接受无参数的类型
  expect(() => new (FunctionToken as unknown as new () => FunctionToken)()).toThrow();

  // null/undefined场景:断言为IFunctionToken类型
  expect(() => new FunctionToken(null as unknown as IFunctionToken)).toThrow();
  expect(() => new FunctionToken(undefined as unknown as IFunctionToken)).toThrow();
});

方法2:使用@ts-expect-error注释

在触发类型错误的代码行上方添加注释,让TypeScript忽略预期内的类型报错:

test('throws an error when token is nullish', function () {
  // @ts-expect-error 预期无参数触发类型错误,用于测试JS环境输入验证
  expect(() => new FunctionToken()).toThrow();

  // @ts-expect-error 预期传入undefined触发类型错误
  expect(() => new FunctionToken(undefined)).toThrow();
  // @ts-expect-error 预期传入null触发类型错误
  expect(() => new FunctionToken(null)).toThrow();
});

这种方式可读性强,能清晰标记出哪些测试是故意绕过类型检查的。

方法3:将类转为any类型

把类转为any后,调用构造函数时将不受类型限制:

test('throws an error when token is nullish', function () {
  const FuncToken = FunctionToken as any;
  expect(() => new FuncToken()).toThrow();
  expect(() => new FuncToken(undefined)).toThrow();
  expect(() => new FuncToken(null)).toThrow();
});

该方法最为简洁,适合批量测试多种非法输入的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:05:16