@osdk/react 2.94.0 → 2.95.0-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/build/browser/new/platform-apis/admin/useCurrentFoundryUser.js.map +1 -1
  3. package/build/browser/new/platform-apis/admin/useFoundryUser.js.map +1 -1
  4. package/build/browser/new/platform-apis/admin/useFoundryUsersList.js.map +1 -1
  5. package/build/browser/new/useLinks.js.map +1 -1
  6. package/build/browser/new/useObjectSet.js.map +1 -1
  7. package/build/browser/new/useOsdkAggregation.js +2 -5
  8. package/build/browser/new/useOsdkAggregation.js.map +1 -1
  9. package/build/browser/new/useOsdkObjects.js.map +1 -1
  10. package/build/browser/util/UserAgent.js +1 -1
  11. package/build/browser/util/UserAgent.js.map +1 -1
  12. package/build/cjs/{chunk-EJT5W6SI.cjs → chunk-YG7PT4LT.cjs} +3 -3
  13. package/build/cjs/chunk-YG7PT4LT.cjs.map +1 -0
  14. package/build/cjs/index.cjs +15 -15
  15. package/build/cjs/public/experimental.cjs +16 -16
  16. package/build/cjs/public/experimental.d.cts +9 -12
  17. package/build/cjs/public/platform-apis.d.cts +1 -4
  18. package/build/esm/new/platform-apis/admin/useCurrentFoundryUser.js.map +1 -1
  19. package/build/esm/new/platform-apis/admin/useFoundryUser.js.map +1 -1
  20. package/build/esm/new/platform-apis/admin/useFoundryUsersList.js.map +1 -1
  21. package/build/esm/new/useLinks.js.map +1 -1
  22. package/build/esm/new/useObjectSet.js.map +1 -1
  23. package/build/esm/new/useOsdkAggregation.js +2 -5
  24. package/build/esm/new/useOsdkAggregation.js.map +1 -1
  25. package/build/esm/new/useOsdkObjects.js.map +1 -1
  26. package/build/esm/util/UserAgent.js +1 -1
  27. package/build/esm/util/UserAgent.js.map +1 -1
  28. package/build/types/new/platform-apis/admin/useCurrentFoundryUser.d.ts +0 -1
  29. package/build/types/new/platform-apis/admin/useCurrentFoundryUser.d.ts.map +1 -1
  30. package/build/types/new/platform-apis/admin/useFoundryUser.d.ts +1 -2
  31. package/build/types/new/platform-apis/admin/useFoundryUser.d.ts.map +1 -1
  32. package/build/types/new/platform-apis/admin/useFoundryUsersList.d.ts +0 -1
  33. package/build/types/new/platform-apis/admin/useFoundryUsersList.d.ts.map +1 -1
  34. package/build/types/new/useLinks.d.ts +2 -2
  35. package/build/types/new/useObjectSet.d.ts +2 -2
  36. package/build/types/new/useOsdkAggregation.d.ts +3 -6
  37. package/build/types/new/useOsdkAggregation.d.ts.map +1 -1
  38. package/build/types/new/useOsdkObjects.d.ts +2 -2
  39. package/docs/actions.mdx +314 -0
  40. package/docs/aggregations.mdx +256 -0
  41. package/docs/cache-invalidation.mdx +229 -0
  42. package/docs/devtools/cache.mdx +29 -0
  43. package/docs/devtools/components.mdx +40 -0
  44. package/docs/devtools/console.mdx +29 -0
  45. package/docs/devtools/index.mdx +151 -0
  46. package/docs/devtools/overview.mdx +45 -0
  47. package/docs/functions.mdx +246 -0
  48. package/docs/index.mdx +62 -0
  49. package/docs/links.mdx +270 -0
  50. package/docs/meta.json +30 -0
  51. package/docs/object-sets.mdx +296 -0
  52. package/docs/objects.mdx +489 -0
  53. package/docs/optimistic-updates.mdx +164 -0
  54. package/docs/platform-apis.mdx +296 -0
  55. package/docs/testing.mdx +348 -0
  56. package/package.json +7 -7
  57. package/build/cjs/chunk-EJT5W6SI.cjs.map +0 -1
  58. package/docs/actions.md +0 -432
  59. package/docs/advanced-queries.md +0 -678
  60. package/docs/cache-management.md +0 -222
  61. package/docs/getting-started.md +0 -319
  62. package/docs/platform-apis.md +0 -234
  63. package/docs/prerequisites.md +0 -48
  64. package/docs/querying-data.md +0 -810
@@ -0,0 +1,296 @@
1
+ ---
2
+ title: Users and markings
3
+ description: Load Foundry users, markings, and CBAC classification banners in React with the hooks in @osdk/react/platform-apis.
4
+ foundryDocs:
5
+ - title: Foundry REST APIs
6
+ path: api/v2/general/overview/introduction
7
+ ---
8
+
9
+ {/* cspell:ignore CBAC cbac refetch refetches */}
10
+
11
+ The hooks in `@osdk/react/platform-apis` call Foundry platform APIs for users and markings with the client from `OsdkProvider`. Use them to show who is signed in, look up other users, list markings, and render classification banners.
12
+
13
+ ## Install the platform packages
14
+
15
+ The hooks depend on two optional peer packages. Install them before importing from `@osdk/react/platform-apis`:
16
+
17
+ ```npm
18
+ npm install @osdk/foundry.admin @osdk/foundry.core
19
+ ```
20
+
21
+ Without them, the bundler fails with `Rollup failed to resolve import "@osdk/foundry.admin"` or a similar error. The rest of `@osdk/react` works without these packages.
22
+
23
+ Every hook needs an `OsdkProvider` above it. The signed-in user's token must allow the platform API you call; a missing permission comes back as an `error`.
24
+
25
+ ## Show the signed-in user
26
+
27
+ `useCurrentFoundryUser` loads the user the client's token belongs to:
28
+
29
+ ```tsx title="src/CurrentUserBadge.tsx"
30
+ import { useCurrentFoundryUser } from "@osdk/react/platform-apis";
31
+
32
+ export function CurrentUserBadge() {
33
+ const { currentUser, isLoading, error } = useCurrentFoundryUser();
34
+
35
+ return (
36
+ <span>
37
+ {currentUser && `Signed in as ${currentUser.givenName ?? currentUser.username}`}
38
+ {isLoading && !error && "Loading…"}
39
+ {error && "Could not load your profile"}
40
+ </span>
41
+ );
42
+ }
43
+ ```
44
+
45
+ | Option | Type | Default | Description |
46
+ | --- | --- | --- | --- |
47
+ | `enabled` | `boolean` | `true` | When `false`, no request is made. |
48
+
49
+ | Field | Type | Description |
50
+ | --- | --- | --- |
51
+ | `currentUser` | `User \| undefined` | The user, with `id`, `username`, `givenName`, `familyName`, `email`, `realm`, `organization`, `status`, and `attributes`. |
52
+ | `isLoading` | `boolean` | `true` while the request runs. |
53
+ | `error` | `Error \| undefined` | Set when the request failed. |
54
+ | `refetch` | `() => void` | Requests the user again. |
55
+
56
+ ## Look up a user
57
+
58
+ `useFoundryUser` takes the user ID as its first argument and options second:
59
+
60
+ ```tsx title="src/UserName.tsx"
61
+ import { useFoundryUser } from "@osdk/react/platform-apis";
62
+
63
+ export function UserName({ userId }: { userId: string }) {
64
+ const { user, error } = useFoundryUser(userId);
65
+ const fullName = [user?.givenName, user?.familyName].filter(Boolean).join(" ");
66
+
67
+ return (
68
+ <span title={error?.message}>
69
+ {error ? "Unknown user" : user ? fullName || user.username : "…"}
70
+ </span>
71
+ );
72
+ }
73
+ ```
74
+
75
+ | Option | Type | Default | Description |
76
+ | --- | --- | --- | --- |
77
+ | `enabled` | `boolean` | `true` | When `false`, no request is made. |
78
+ | `status` | `"ACTIVE" \| "DELETED"` | `"ACTIVE"` | Status of the user to look up. Pass `"DELETED"` to resolve users who have been removed. |
79
+
80
+ The result has `user`, `isLoading`, `error`, and `refetch`. A new `userId` triggers a new request.
81
+
82
+ ## List users
83
+
84
+ `useFoundryUsersList` returns one page of users. Pass the previous page's `nextPageToken` as `pageToken` to load the next one:
85
+
86
+ ```tsx title="src/UserDirectory.tsx"
87
+ import { useFoundryUsersList } from "@osdk/react/platform-apis";
88
+ import { useState } from "react";
89
+
90
+ export function UserDirectory() {
91
+ const [pageToken, setPageToken] = useState<string | undefined>();
92
+ const { users, nextPageToken, isLoading, error } = useFoundryUsersList({
93
+ pageSize: 50,
94
+ pageToken,
95
+ });
96
+
97
+ return (
98
+ <div>
99
+ {error && <p role="alert">Could not load users.</p>}
100
+ {isLoading && !error && <p>Loading…</p>}
101
+ <ul>
102
+ {users?.map((user) => (
103
+ <li key={user.id}>{user.username}</li>
104
+ ))}
105
+ </ul>
106
+ <button
107
+ disabled={nextPageToken == null || isLoading}
108
+ onClick={() => setPageToken(nextPageToken)}
109
+ >
110
+ Next page
111
+ </button>
112
+ </div>
113
+ );
114
+ }
115
+ ```
116
+
117
+ | Option | Type | Default | Description |
118
+ | --- | --- | --- | --- |
119
+ | `enabled` | `boolean` | `true` | When `false`, no request is made. |
120
+ | `include` | `"ACTIVE" \| "DELETED"` | `"ACTIVE"` | Which users to list. |
121
+ | `pageSize` | `number` | `1000` | Preferred page size. The server can return more or fewer. |
122
+ | `pageToken` | `string` | `undefined` | Token for the page to load. Omit for the first page. |
123
+
124
+ | Field | Type | Description |
125
+ | --- | --- | --- |
126
+ | `users` | `User[] \| undefined` | The users on this page. |
127
+ | `nextPageToken` | `string \| undefined` | Token for the next page. `undefined` on the last page. |
128
+ | `isLoading`, `error`, `refetch` | | As for `useCurrentFoundryUser`. |
129
+
130
+ Each page replaces the previous one. To show every page loaded so far, keep the users you have received in state.
131
+
132
+ ## List markings
133
+
134
+ `useMarkings` lists the markings the user can see, and `useMarkingCategories` lists the categories they belong to. Join them on `marking.categoryId`:
135
+
136
+ ```tsx title="src/MarkingList.tsx"
137
+ import { useMarkingCategories, useMarkings } from "@osdk/react/platform-apis";
138
+
139
+ export function MarkingList() {
140
+ const { markings, error: markingsError } = useMarkings({ includeDeleted: false });
141
+ const { categories, error: categoriesError } = useMarkingCategories({
142
+ includeDeleted: false,
143
+ });
144
+
145
+ const categoryName = new Map(categories?.map((c) => [c.id, c.name] as const));
146
+
147
+ return (
148
+ <div>
149
+ {(markingsError ?? categoriesError) && <p role="alert">Could not load markings.</p>}
150
+ <ul>
151
+ {markings?.map((marking) => (
152
+ <li key={marking.id}>
153
+ {categoryName.get(marking.categoryId) ?? "Other"}: {marking.name}
154
+ </li>
155
+ ))}
156
+ </ul>
157
+ </div>
158
+ );
159
+ }
160
+ ```
161
+
162
+ | Hook | Option | Default | Returns |
163
+ | --- | --- | --- | --- |
164
+ | `useMarkings` | `includeDeleted` | `true` | `markings`: `Marking[]`, each with `id`, `categoryId`, `name`, `description`, and `deleted`. |
165
+ | `useMarkingCategories` | `includeDeleted` | `true` | `categories`: `MarkingCategory[]`, each with `id`, `name`, `description`, `markings` (marking IDs), and `deleted`. |
166
+ | Both | `markingType` | All types | Only markings or categories of this type, such as `"CBAC"`. |
167
+
168
+ Both accept `enabled` and return `isLoading`, `error`, and `refetch`. Deleted entries are included unless you pass `includeDeleted: false`.
169
+
170
+ ## Get a user's markings
171
+
172
+ `useUserViewMarkings` returns the IDs of the markings a user can view. Without `userId`, it uses the signed-in user:
173
+
174
+ ```tsx title="src/useCanView.ts"
175
+ import { useUserViewMarkings } from "@osdk/react/platform-apis";
176
+
177
+ export function useCanView(requiredMarkingIds: string[]) {
178
+ const { markingIds, isLoading, error } = useUserViewMarkings();
179
+ const viewable = new Set(markingIds);
180
+
181
+ return {
182
+ canView: markingIds != null && requiredMarkingIds.every((id) => viewable.has(id)),
183
+ isLoading,
184
+ error,
185
+ };
186
+ }
187
+ ```
188
+
189
+ | Option | Type | Default | Description |
190
+ | --- | --- | --- | --- |
191
+ | `userId` | `string` | Signed-in user | The user to look up. |
192
+ | `enabled` | `boolean` | `true` | When `false`, no request is made. |
193
+
194
+ The result has `markingIds` (`string[] | undefined`), `isLoading`, `error`, and `refetch`.
195
+
196
+ ## Show a classification banner
197
+
198
+ For classification-based access control (CBAC), `useCbacBanner` returns the banner text and colors for a set of marking IDs:
199
+
200
+ ```tsx title="src/ClassificationBanner.tsx"
201
+ import { useCbacBanner } from "@osdk/react/platform-apis";
202
+
203
+ export function ClassificationBanner({ markingIds }: { markingIds: string[] }) {
204
+ const { banner, error } = useCbacBanner({ markingIds });
205
+
206
+ if (error != null || banner == null) {
207
+ return null;
208
+ }
209
+ const [first, ...rest] = banner.backgroundColors;
210
+ const background =
211
+ rest.length > 0 ? `linear-gradient(90deg, ${banner.backgroundColors.join(", ")})` : first;
212
+
213
+ return (
214
+ <div role="banner" style={{ background, color: banner.textColor, textAlign: "center" }}>
215
+ {banner.classificationString}
216
+ </div>
217
+ );
218
+ }
219
+ ```
220
+
221
+ | Field | Type | Description |
222
+ | --- | --- | --- |
223
+ | `banner.classificationString` | `string` | The banner text. |
224
+ | `banner.textColor` | `string` | Text color. |
225
+ | `banner.backgroundColors` | `string[]` | One or more background colors. |
226
+ | `banner.markingIds` | `string[]` | The markings the banner represents. |
227
+
228
+ `useCbacMarkingRestrictions` checks a proposed set of marking IDs before you apply it, for example in a marking picker:
229
+
230
+ | Field | Type | Description |
231
+ | --- | --- | --- |
232
+ | `restrictions.isValid` | `boolean` | Whether the markings form a valid classification: none are disallowed and every required constraint is met. |
233
+ | `restrictions.userSatisfiesMarkings` | `boolean` | Whether the signed-in user satisfies the markings. |
234
+ | `restrictions.impliedMarkings` | `string[]` | Markings that the selection implies. |
235
+ | `restrictions.disallowedMarkings` | `string[]` | Markings that are disallowed with the selection. |
236
+ | `restrictions.requiredMarkings` | `string[][]` | Required marking constraints, as groups of marking IDs. |
237
+
238
+ Both hooks take `{ markingIds, enabled? }`, return `isLoading`, `error`, and `refetch`, and make no request while `markingIds` is empty. `useCbacMarkingRestrictions` calls a beta endpoint in preview mode, which must be enabled on your Foundry stack. For a ready-made picker, see the [CbacPicker component](/components/cbac-picker).
239
+
240
+ ## How these hooks load data
241
+
242
+ These hooks do not use the object cache that powers `useOsdkObjects` and the other ontology hooks:
243
+
244
+ - Each mounted hook makes its own request. Two components that call `useCurrentFoundryUser` make two requests. Call the hook once and pass the result down when that matters.
245
+ - A hook requests again when an option changes. `refetch` requests again on demand.
246
+ - While a request runs, the previous result is cleared and the data field is `undefined`.
247
+ - When a request fails, `isLoading` stays `true` next to `error`. Check `error` before `isLoading`, as the examples on this page do.
248
+
249
+ ## Handle errors
250
+
251
+ All hooks return failures as an `Error`. When the failure comes from a Foundry API, it is a `PalantirApiError`, exported from `@osdk/client`. Narrow with `instanceof` to read its fields, all of which are optional:
252
+
253
+ | Field | Type | Description |
254
+ | --- | --- | --- |
255
+ | `errorName` | `string` | Stable identifier, such as `UserNotFound`. Switch on this. |
256
+ | `errorCode` | `string` | Error category, such as `NOT_FOUND` or `PERMISSION_DENIED`. |
257
+ | `errorDescription` | `string` | Human-readable description. |
258
+ | `statusCode` | `number` | HTTP status. |
259
+ | `errorInstanceId` | `string` | Server-side ID for this occurrence. Include it in bug reports. |
260
+ | `parameters` | `object` | Extra context from the server, such as `{ userId }`. |
261
+
262
+ ```tsx title="src/describePlatformError.ts"
263
+ import { PalantirApiError } from "@osdk/client";
264
+
265
+ export function describePlatformError(error: Error): string {
266
+ if (!(error instanceof PalantirApiError)) {
267
+ return error.message;
268
+ }
269
+ if (error.errorName === "UserNotFound") {
270
+ return "We couldn't find that user.";
271
+ }
272
+ if (error.errorCode === "PERMISSION_DENIED") {
273
+ return "You don't have permission to see this.";
274
+ }
275
+ return `${error.errorDescription ?? error.message} (error ID: ${error.errorInstanceId ?? "unknown"})`;
276
+ }
277
+ ```
278
+
279
+ Use it with any hook on this page:
280
+
281
+ ```tsx title="src/UserCard.tsx"
282
+ import { useFoundryUser } from "@osdk/react/platform-apis";
283
+ import { describePlatformError } from "./describePlatformError";
284
+
285
+ export function UserCard({ userId }: { userId: string }) {
286
+ const { user, error } = useFoundryUser(userId);
287
+
288
+ return (
289
+ <article>
290
+ {error && <p role="alert">{describePlatformError(error)}</p>}
291
+ {user && <h2>{user.username}</h2>}
292
+ {user?.email && <p>{user.email}</p>}
293
+ </article>
294
+ );
295
+ }
296
+ ```
@@ -0,0 +1,348 @@
1
+ ---
2
+ title: Test your app
3
+ description: Unit test OSDK React components with Vitest and Testing Library, using @osdk/react/testing and the mocks in @osdk/unit-testing.
4
+ foundryDocs:
5
+ - title: Unit testing OSDK code
6
+ path: ontology-sdk/typescript-osdk-testing
7
+ ---
8
+
9
+ {/* cspell:ignore jsdom msw MSW stubbable */}
10
+
11
+ Test components that use `@osdk/react` without a Foundry stack. Stub the hooks a component calls, give components that read the OSDK context a test provider, and use mock clients and objects from `@osdk/unit-testing` for code that calls the client directly.
12
+
13
+ ## Choose an approach
14
+
15
+ | What the code under test uses | Approach | Tools |
16
+ | --- | --- | --- |
17
+ | Ontology hooks: `useOsdkObjects`, `useOsdkObject`, `useOsdkAction`, `useOsdkFunction`, and the rest | Replace the hook with a stub that returns the state you want to test | `vi.mock`, `createMockOsdkObject` |
18
+ | `useOsdkClient`, `useObservableClient`, or the hooks in `@osdk/react/platform-apis` | Render inside `TestOsdkProvider` | `@osdk/react/testing`, `createMockClient`, MSW |
19
+ | The `Client` directly, in a helper or hook | Pass a mock client with stubbed responses | `createMockClient`, `createMockObjectSet` |
20
+
21
+ Stubbing the ontology hooks keeps tests fast and lets you set loading, error, and optimistic states directly. The mock client from `@osdk/unit-testing` cannot power `OsdkProvider` or the ontology hooks, because they need the observable client that `OsdkProvider` builds from a real client.
22
+
23
+ ## Set up
24
+
25
+ Install Vitest, a DOM environment, Testing Library, and the OSDK test helpers. `@osdk/unit-testing` has `@osdk/functions` as a peer dependency, and MSW is only needed for the platform API example:
26
+
27
+ ```npm
28
+ npm install --save-dev vitest jsdom @testing-library/react @vitejs/plugin-react @osdk/unit-testing @osdk/functions msw
29
+ ```
30
+
31
+ Run tests in a DOM environment:
32
+
33
+ ```ts title="vitest.config.ts"
34
+ import react from "@vitejs/plugin-react";
35
+ import { defineConfig } from "vitest/config";
36
+
37
+ export default defineConfig({
38
+ plugins: [react()],
39
+ test: {
40
+ environment: "jsdom",
41
+ },
42
+ });
43
+ ```
44
+
45
+ `TestOsdkProvider` and `fakeObservableClient` ship in `@osdk/react` under `@osdk/react/testing`, so they need no extra install.
46
+
47
+ ## Test a component that loads objects
48
+
49
+ This component lists employees with `useOsdkObjects`:
50
+
51
+ ```tsx title="src/EmployeeList.tsx"
52
+ import { Employee } from "@my-app/sdk";
53
+ import { useOsdkObjects } from "@osdk/react";
54
+
55
+ export function EmployeeList() {
56
+ const { data, isLoading, error } = useOsdkObjects(Employee, {
57
+ orderBy: { fullName: "asc" },
58
+ });
59
+
60
+ return (
61
+ <div>
62
+ {isLoading && <p>Loading…</p>}
63
+ {error && <p role="alert">{error.message}</p>}
64
+ <ul>
65
+ {data?.map((employee) => (
66
+ <li key={employee.$primaryKey}>{employee.fullName}</li>
67
+ ))}
68
+ </ul>
69
+ </div>
70
+ );
71
+ }
72
+ ```
73
+
74
+ Replace `useOsdkObjects` with a Vitest mock, keep the rest of `@osdk/react` real, and build objects with `createMockOsdkObject`:
75
+
76
+ ```tsx title="src/EmployeeList.test.tsx"
77
+ import { Employee } from "@my-app/sdk";
78
+ import { useOsdkObjects } from "@osdk/react";
79
+ import { createMockOsdkObject } from "@osdk/unit-testing";
80
+ import { cleanup, render, screen } from "@testing-library/react";
81
+ import { afterEach, describe, expect, it, vi } from "vitest";
82
+ import { EmployeeList } from "./EmployeeList";
83
+
84
+ vi.mock("@osdk/react", async (importOriginal) => ({
85
+ ...(await importOriginal<typeof import("@osdk/react")>()),
86
+ useOsdkObjects: vi.fn(),
87
+ }));
88
+
89
+ type ListResult = ReturnType<typeof useOsdkObjects>;
90
+
91
+ function listResult(
92
+ overrides: Omit<Partial<ListResult>, "data"> & { data?: unknown[] },
93
+ ): ListResult {
94
+ return {
95
+ data: undefined,
96
+ isLoading: false,
97
+ error: undefined,
98
+ isOptimistic: false,
99
+ hasMore: false,
100
+ fetchMore: undefined,
101
+ objectSet: undefined,
102
+ refetch: vi.fn(),
103
+ ...overrides,
104
+ } as ListResult;
105
+ }
106
+
107
+ describe("EmployeeList", () => {
108
+ afterEach(cleanup);
109
+
110
+ it("renders employees", () => {
111
+ const ada = createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" });
112
+ const alan = createMockOsdkObject(Employee, { employeeId: 2, fullName: "Alan Turing" });
113
+ vi.mocked(useOsdkObjects).mockReturnValue(
114
+ listResult({ data: [ada, alan] }),
115
+ );
116
+
117
+ render(<EmployeeList />);
118
+
119
+ expect(screen.getAllByRole("listitem").map((li) => li.textContent)).toEqual([
120
+ "Ada Lovelace",
121
+ "Alan Turing",
122
+ ]);
123
+ });
124
+
125
+ it("keeps rendering data while it reloads", () => {
126
+ const ada = createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" });
127
+ vi.mocked(useOsdkObjects).mockReturnValue(
128
+ listResult({ data: [ada], isLoading: true }),
129
+ );
130
+
131
+ render(<EmployeeList />);
132
+
133
+ expect(screen.getByText("Loading…")).toBeTruthy();
134
+ expect(screen.getByText("Ada Lovelace")).toBeTruthy();
135
+ });
136
+
137
+ it("shows errors", () => {
138
+ vi.mocked(useOsdkObjects).mockReturnValue(
139
+ listResult({ error: new Error("Permission denied") }),
140
+ );
141
+
142
+ render(<EmployeeList />);
143
+
144
+ expect(screen.getByRole("alert").textContent).toBe("Permission denied");
145
+ });
146
+
147
+ it("asks for employees sorted by name", () => {
148
+ vi.mocked(useOsdkObjects).mockReturnValue(listResult({}));
149
+
150
+ render(<EmployeeList />);
151
+
152
+ expect(useOsdkObjects).toHaveBeenCalledWith(Employee, {
153
+ orderBy: { fullName: "asc" },
154
+ });
155
+ });
156
+ });
157
+ ```
158
+
159
+ `createMockOsdkObject(type, properties, options?)` returns an object instance with `$apiName`, `$objectType`, `$primaryKey`, `$rid`, `$clone`, and `$link`. The primary key property must be in `properties`. Pass `options.links` to stub linked objects, and `options.titlePropertyApiName` to set `$title`.
160
+
161
+ ## Test a component that applies an action
162
+
163
+ Stub `useOsdkAction` and assert on the `applyAction` mock. This test drives the `PromoteButton` from [Apply actions](./actions.mdx):
164
+
165
+ ```tsx title="src/PromoteButton.test.tsx"
166
+ import { Employee } from "@my-app/sdk";
167
+ import { useOsdkAction } from "@osdk/react";
168
+ import { createMockOsdkObject } from "@osdk/unit-testing";
169
+ import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
170
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
171
+ import { PromoteButton } from "./PromoteButton";
172
+
173
+ vi.mock("@osdk/react", async (importOriginal) => ({
174
+ ...(await importOriginal<typeof import("@osdk/react")>()),
175
+ useOsdkAction: vi.fn(),
176
+ }));
177
+
178
+ const applyAction = vi.fn();
179
+
180
+ function actionResult(overrides: Partial<ReturnType<typeof useOsdkAction>> = {}) {
181
+ return {
182
+ applyAction,
183
+ validateAction: vi.fn(),
184
+ data: undefined,
185
+ error: undefined,
186
+ isPending: false,
187
+ isValidating: false,
188
+ validationResult: undefined,
189
+ ...overrides,
190
+ };
191
+ }
192
+
193
+ describe("PromoteButton", () => {
194
+ const employee = createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" });
195
+
196
+ beforeEach(() => {
197
+ applyAction.mockReset().mockResolvedValue(undefined);
198
+ vi.mocked(useOsdkAction).mockReturnValue(actionResult());
199
+ });
200
+ afterEach(cleanup);
201
+
202
+ it("applies modifyEmployee with the new title", async () => {
203
+ render(<PromoteButton employee={employee} jobTitle="Staff Engineer" />);
204
+
205
+ fireEvent.click(screen.getByRole("button", { name: "Make Staff Engineer" }));
206
+
207
+ await waitFor(() =>
208
+ expect(applyAction).toHaveBeenCalledWith({ employee, jobTitle: "Staff Engineer" }),
209
+ );
210
+ });
211
+
212
+ it("disables the button while the action runs", () => {
213
+ vi.mocked(useOsdkAction).mockReturnValue(actionResult({ isPending: true }));
214
+
215
+ render(<PromoteButton employee={employee} jobTitle="Staff Engineer" />);
216
+
217
+ expect(screen.getByRole("button").hasAttribute("disabled")).toBe(true);
218
+ });
219
+
220
+ it("shows the failure", () => {
221
+ vi.mocked(useOsdkAction).mockReturnValue(
222
+ actionResult({ error: { unknown: new Error("Network error") } }),
223
+ );
224
+
225
+ render(<PromoteButton employee={employee} jobTitle="Staff Engineer" />);
226
+
227
+ expect(screen.getByRole("alert").textContent).toContain("Could not update");
228
+ });
229
+ });
230
+ ```
231
+
232
+ The hook's state does not change by itself when the mock is called, so set `isPending`, `error`, or `validationResult` in each test rather than expecting `applyAction` to update them. To simulate a rejection, use `applyAction.mockRejectedValue(new Error("..."))`.
233
+
234
+ ## Provide the OSDK context
235
+
236
+ `TestOsdkProvider` from `@osdk/react/testing` puts a `client` and an `observableClient` of your choice into context, without the devtools and user-agent setup of `OsdkProvider`. Use it when the code under test calls `useOsdkClient`, `useObservableClient`, or a platform API hook.
237
+
238
+ | Export | Description |
239
+ | --- | --- |
240
+ | `TestOsdkProvider` | Provider with `client` and `observableClient` props, both required. Use it only in tests. |
241
+ | `fakeObservableClient` | An `ObservableClient` whose every method throws. Pass it when the code under test never uses the observable client, so an unexpected call fails loudly. |
242
+
243
+ Platform API hooks call Foundry over HTTP with the context's `client`. A client from `createMockClient` sends those requests to `https://mock.invalid/`, so intercept them with MSW. This test renders the `CurrentUserBadge` from [Users and markings](./platform-apis.mdx):
244
+
245
+ ```tsx title="src/CurrentUserBadge.test.tsx"
246
+ import { fakeObservableClient, TestOsdkProvider } from "@osdk/react/testing";
247
+ import { createMockClient } from "@osdk/unit-testing";
248
+ import { cleanup, render, screen } from "@testing-library/react";
249
+ import { http, HttpResponse } from "msw";
250
+ import { setupServer } from "msw/node";
251
+ import { afterAll, afterEach, beforeAll, expect, it } from "vitest";
252
+ import { CurrentUserBadge } from "./CurrentUserBadge";
253
+
254
+ const server = setupServer();
255
+
256
+ beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
257
+ afterEach(() => {
258
+ server.resetHandlers();
259
+ cleanup();
260
+ });
261
+ afterAll(() => server.close());
262
+
263
+ it("greets the signed-in user", async () => {
264
+ server.use(
265
+ http.get("https://mock.invalid/api/v2/admin/users/getCurrent", () =>
266
+ HttpResponse.json({
267
+ id: "user-1",
268
+ username: "ada",
269
+ givenName: "Ada",
270
+ realm: "default",
271
+ status: "ACTIVE",
272
+ attributes: {},
273
+ }),
274
+ ),
275
+ );
276
+
277
+ render(
278
+ <TestOsdkProvider client={createMockClient()} observableClient={fakeObservableClient}>
279
+ <CurrentUserBadge />
280
+ </TestOsdkProvider>,
281
+ );
282
+
283
+ expect(await screen.findByText("Signed in as Ada")).toBeTruthy();
284
+ });
285
+ ```
286
+
287
+ ## Test code that calls the client
288
+
289
+ For a helper or hook that calls the `Client` itself, pass a client from `createMockClient` and register the responses it should get. Stubs match on the exact chain of calls, including arguments:
290
+
291
+ ```ts title="src/loadDepartmentRoster.ts"
292
+ import { Employee } from "@my-app/sdk";
293
+ import type { Client } from "@osdk/client";
294
+
295
+ export async function loadDepartmentRoster(client: Client, department: string) {
296
+ const page = await client(Employee)
297
+ .where({ department: { $eq: department } })
298
+ .fetchPage();
299
+ return page.data.map((employee) => employee.fullName ?? "Unknown");
300
+ }
301
+ ```
302
+
303
+ ```ts title="src/loadDepartmentRoster.test.ts"
304
+ import { Employee, getEmployeeMetrics } from "@my-app/sdk";
305
+ import { createMockClient, createMockOsdkObject } from "@osdk/unit-testing";
306
+ import { expect, it } from "vitest";
307
+ import { loadDepartmentRoster } from "./loadDepartmentRoster";
308
+
309
+ it("lists the people in a department", async () => {
310
+ const client = createMockClient();
311
+ client
312
+ .when((stub) =>
313
+ stub(Employee)
314
+ .where({ department: { $eq: "Platform" } })
315
+ .fetchPage(),
316
+ )
317
+ .thenReturnObjects([
318
+ createMockOsdkObject(Employee, { employeeId: 1, fullName: "Ada Lovelace" }),
319
+ ]);
320
+
321
+ expect(await loadDepartmentRoster(client, "Platform")).toEqual(["Ada Lovelace"]);
322
+ });
323
+
324
+ it("stubs function calls", async () => {
325
+ const client = createMockClient();
326
+ client.whenQuery(getEmployeeMetrics, { department: "Sales" }).thenReturn({ headcount: 12 });
327
+
328
+ const result = await client(getEmployeeMetrics).executeFunction({ department: "Sales" });
329
+
330
+ expect(result).toEqual({ headcount: 12 });
331
+ });
332
+ ```
333
+
334
+ A call with no matching stub throws, with `No stub for request` for object set calls or `No stub for query '<name>'` for functions. When several stubs match, the last one registered wins.
335
+
336
+ ### `@osdk/unit-testing` reference
337
+
338
+ | Export | Description |
339
+ | --- | --- |
340
+ | `createMockClient()` | A `Client` whose responses you stub. Use it with `TestOsdkProvider` or pass it to code that takes a `Client`. It does not stub actions. |
341
+ | `client.when(callback)` | Stub an object set call chain that ends in `fetchPage`, `fetchOne`, `aggregate`, or similar. Complete it with `thenReturnObjects`, `thenReturnObject`, or `thenReturnAggregation`, depending on the call. |
342
+ | `client.whenObjectSet(objectSet, callback)` | Stub calls on an object set created with `createMockObjectSet`, for code that takes an `ObjectSet` argument. |
343
+ | `client.whenQuery(fn, params?)` | Stub a function call. Complete it with `thenReturn(value)` or `thenThrow(error)`. |
344
+ | `client.clearStubs()` | Remove every stub. |
345
+ | `createMockOsdkObject(type, properties, options?)` | An object instance. See [Test a component that loads objects](#test-a-component-that-loads-objects). |
346
+ | `createMockObjectSet(type)` | A standalone object set to pass as an argument and stub with `whenObjectSet`. |
347
+ | `createMockAttachment(rid, blob?, metadata?)` | An attachment whose `fetchContents` and `fetchMetadata` return the given values. |
348
+ | `createMockWriteableClient()` | A mock client that records edits, for testing Foundry functions written with `@osdk/functions`. Read the edits with `getEdits()`. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@osdk/react",
3
- "version": "2.94.0",
3
+ "version": "2.95.0-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -90,8 +90,8 @@
90
90
  "@types/react": "^17 || ^18 || ^19",
91
91
  "react": "^17 || ^18 || ^19",
92
92
  "react-dom": "^17 || ^18 || ^19",
93
- "@osdk/api": "^2.94.0",
94
- "@osdk/client": "^2.94.0"
93
+ "@osdk/api": "^2.95.0-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a",
94
+ "@osdk/client": "^2.95.0-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a"
95
95
  },
96
96
  "peerDependenciesMeta": {
97
97
  "@osdk/foundry.admin": {
@@ -116,12 +116,12 @@
116
116
  "react": "^18.3.1",
117
117
  "tiny-invariant": "^1.3.3",
118
118
  "typescript": "~5.5.4",
119
- "@osdk/api": "2.94.0",
119
+ "@osdk/api": "2.95.0-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a",
120
+ "@osdk/client": "2.95.0-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a",
121
+ "@osdk/client.test.ontology": "2.94.1-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a",
120
122
  "@osdk/monorepo.api-extractor": "~0.7.0",
121
123
  "@osdk/monorepo.tsconfig": "~0.7.0",
122
- "@osdk/client.test.ontology": "2.94.0",
123
- "@osdk/client": "2.94.0",
124
- "@osdk/shared.test.intellisense": "~0.41.0"
124
+ "@osdk/shared.test.intellisense": "~0.41.1-main-a5bdff2e9db1a01e5858042ee5232cb13c13368a"
125
125
  },
126
126
  "publishConfig": {
127
127
  "access": "public"