TS单元测试中Object Search返回undefined问题求助
解决方案
在Palantir Foundry的单元测试中,直接通过Objects.create()创建的对象不会自动被Objects.search()检索到,需要通过测试上下文显式注册到对应的对象集合中。同时需注意对象类型名称的一致性,以下是修正后的测试代码及关键说明:
修正后的测试代码
import { MyFunctionLibrary } from '../src/subfolder/file'; import { ObjectTestContext, Objects } from '@foundry/functions-api/testing'; describe("MyFunctionLibrary Tests", () => { let myFunctionLibrary: MyFunctionLibrary; let testContext: ObjectTestContext; beforeEach(() => { myFunctionLibrary = new MyFunctionLibrary(); testContext = new ObjectTestContext(); // 绑定测试上下文,让Objects搜索基于该上下文的对象集合 Objects.setTestContext(testContext); }); test("do something", async () => { // 创建测试对象 const x1 = Objects.create().xType("x1"); const x2 = Objects.create().xType("x2"); const y = Objects.create().zType("y"); y.links.add(x1); y.links.add(x2); // 将对象注册到对应类型的ObjectSet中 testContext.addToObjectSet("xType", [x1, x2]); // 注意:创建y时使用的是zType,搜索时需对应使用zType而非yType testContext.addToObjectSet("zType", [y]); // 现在检索能正确获取到对象集合 const os1 = Objects.search().zType(); const os2 = Objects.search().xType(); // 验证对象集合内容 expect(await os1.allAsync()).toHaveLength(1); expect(await os2.allAsync()).toHaveLength(2); // 调用目标函数 myFunctionLibrary.doSomething(os1, os2); // 添加你的断言逻辑,验证函数输出或行为 }); });
关键说明
测试上下文绑定:
使用ObjectTestContext管理测试环境中的对象集合,并通过Objects.setTestContext()将搜索行为绑定到该上下文,确保Objects.search()只返回你注册的测试对象。对象注册:
创建对象后必须通过testContext.addToObjectSet(typeName, objectsArray)将对象加入对应类型的集合,否则Objects.search()会返回空/undefined。类型名称匹配:
你代码中创建y对象时使用了zType("y"),但后续搜索用了yType(),这是典型的类型名称不匹配问题,会直接导致搜索不到对象,需保证创建和搜索的类型名称完全一致。模拟ObjectSet操作:
若需要模拟take()、filter()等ObjectSet方法,可直接通过测试上下文构造的ObjectSet调用,例如:// 模拟只取第一个zType对象的ObjectSet const filteredOs = testContext.objectSet("zType", [y]).take(1);
内容的提问来源于stack exchange,提问作者Brendan Manning
相关产品推荐
相关产品推荐

