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

如何用Node.js的assert实现Jest中对象属性类型断言的等效功能?

Node.js测试运行器中等效Jest expect.any的写法

在Jest中我们可以通过expect.any(Date)这类语法,轻松验证对象属性的类型,同时匹配固定值属性。如果改用Node.js内置的assert模块,有两种常用实现方式:

方式一:拆分独立断言

这种方式直观易懂,适合简单场景:

import assert from 'node:assert';

// 验证固定属性值
assert.strictEqual(myObj.foo, 'bar');
// 验证now是Date实例
assert.ok(myObj.now instanceof Date);
// 验证count是数字类型
assert.strictEqual(typeof myObj.count, 'number');

方式二:自定义匹配器(接近Jest写法)

如果想要和Jest的写法风格更一致,可以通过assert.deepEqual的自定义比较函数实现类型匹配占位符:

import assert from 'node:assert';

// 自定义类型匹配工具函数
const any = (targetType) => ({ __expectedType__: targetType });

assert.deepEqual(myObj, {
  now: any(Date),
  count: any(Number),
  foo: 'bar'
}, undefined, (actualValue, expectedValue) => {
  // 处理自定义类型匹配
  if (expectedValue?.__expectedType__) {
    const type = expectedValue.__expectedType__;
    if (type === Date) {
      return actualValue instanceof Date;
    }
    if (type === Number) {
      return typeof actualValue === 'number';
    }
    // 可根据需求扩展其他类型,比如String、Boolean等
    return false;
  }
  // 非自定义匹配的属性,使用默认的深度比较逻辑
  return undefined;
});

第二种方式里,any函数生成的标记对象会被自定义比较函数识别,完成类型验证,写法上和Jest的expect.any高度相似。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 14:11:09