When writing unit tests you may want to create canned answers (also called "stubs") for object sets searches or object aggregations to dictate the responses to the calls your code is making when writing unit tests. You need to import { whenObjectSet } from "@foundry/functions-testing-lib" to use stubs.
Copied!1 2 3 4 5 6import { Objects } from "@foundry/ontology-api"; const objectSet = Objects.search().objectType(); expect(myFunctions.filterObjectSet(objectSet)) .toEqual(objectSet.filter(s => s.prop.range().gte(0)))
You can define the response to aggregation calls using stubs.
Copied!1 2 3import { whenObjectSet } from "@foundry/functions-testing-lib" whenObjectSet(Objects.search().objectType().sum(s => s.property)).thenReturn(55);
This means that whenever Objects.search().objectType().sum(s => s.property)) is run, the result will be 55.
You can also define the response to certain object searches using stubs.
Copied!1 2 3 4import { whenObjectSet } from "@foundry/functions-testing-lib"; whenObjectSet(Objects.search().objectType().orderBy().takeAsync(10)).thenReturn([employeeObj]) await expect(myFunctions.aggregateSum(objectSet)).resolves.toEqual(65);
This means that whenever this particular objects search aggregation is run, the property sum will resolve to 65.
You can mock multiple specific object set searches by overloading the search constructor. You must give each object a rid property.
Copied!1 2 3 4 5 6 7 8 9 10import { whenObjectSet } from "@foundry/functions-testing-lib"; const objA = Objects.create().objectType('a'); const objB = Objects.create().objectType('b'); objA.rid = 'ridA'; objB.rid = 'ridB'; whenObjectSet(Objects.search().ObjType([objA]).all()).thenReturn([objA]); whenObjectSet(Objects.search().ObjType([objB, objB]).all()).thenReturn([objA, objB]);
You can stub a searchAround traversal in the same way as any other object set search, including when you start from a single object and convert it with the search constructor. The traversal method name is generated from the link type field name, and you must give each object you pass to the search constructor a rid property.
Copied!1 2 3 4 5 6 7 8import { whenObjectSet } from "@foundry/functions-testing-lib"; const objA = Objects.create().objectType('a'); const objB = Objects.create().objectType('b'); objA.rid = 'ridA'; whenObjectSet(Objects.search().ObjType([objA]).searchAroundLinkField().all()).thenReturn([objB]);
For examples of setting link state on stub objects, review Verify Ontology edits.