如何用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
相关产品推荐
相关产品推荐

