From 34a615ad43b9742c5ef3cf92e98c6bb3fe5d5f25 Mon Sep 17 00:00:00 2001 From: Rudy Fraser Date: Tue, 10 Nov 2026 16:39:53 -0500 Subject: [PATCH] test(merge): migrate draft, fallback and engagement tests to the lex clients --- .../streamplace/__tests__/visible.test.ts | 4 +- .../__tests__/notifications-test.ts | 19 ++-- .../__tests__/appview-fallback-probe.test.ts | 70 ++++++++------- src/state/__tests__/appview-fallback.test.ts | 90 ++++++++++++------- .../__tests__/profile-enrichment.test.tsx | 12 +-- .../space-engagement-routing.test.ts | 66 +++++--------- .../drafts/state/__tests__/api-event.test.ts | 23 +++-- .../drafts/state/__tests__/api-poll.test.ts | 27 ++++-- .../shell/__tests__/Composer-context.test.tsx | 9 +- 9 files changed, 177 insertions(+), 143 deletions(-) diff --git a/src/features/streamplace/__tests__/visible.test.ts b/src/features/streamplace/__tests__/visible.test.ts index b04388b88..b914321cf 100644 --- a/src/features/streamplace/__tests__/visible.test.ts +++ b/src/features/streamplace/__tests__/visible.test.ts @@ -2,8 +2,8 @@ import {type ModerationOpts} from '@bsky/sdk/moderation' import {visibleMessages} from '../visible' -jest.mock('@atproto/api', () => ({ - ...jest.requireActual('@atproto/api'), +jest.mock('@bsky/sdk/moderation', () => ({ + ...jest.requireActual('@bsky/sdk/moderation'), moderateProfile: (p: {did: string}) => ({ ui: () => ({filter: p.did === 'did:muted', blur: p.did === 'did:warned'}), }), diff --git a/src/lib/notifications/__tests__/notifications-test.ts b/src/lib/notifications/__tests__/notifications-test.ts index 2c66f7745..13dffbdbf 100644 --- a/src/lib/notifications/__tests__/notifications-test.ts +++ b/src/lib/notifications/__tests__/notifications-test.ts @@ -2,6 +2,7 @@ import {type Client} from '@atproto/lex' import * as Notifications from 'expo-notifications' import {PUBLIC_APPVIEW_DID} from '#/lib/constants' +import {app} from '#/lexicons' import {unregisterPushToken} from '#/lib/notifications/notifications' jest.mock('expo-notifications', () => ({ @@ -11,7 +12,7 @@ jest.mock('expo-notifications', () => ({ setBadgeCountAsync: jest.fn(), })) jest.mock('#/state/session', () => ({ - useAgent: jest.fn(), + useAppviewClient: jest.fn(), useSession: jest.fn(), })) jest.mock('#/analytics', () => ({useAnalytics: jest.fn()})) @@ -21,12 +22,9 @@ jest.mock('#/../modules/expo-background-notification-handler', () => ({ })) describe('unregisterPushToken', () => { - it('uses the account service when an OAuth client has no serviceUrl', async () => { - const unregisterPush = jest.fn().mockResolvedValue(undefined) - const client = { - app: {bsky: {notification: {unregisterPush}}}, - session: {handle: 'alice.test'}, - } as unknown as AtpAgent + it('unregisters from the appview that matches the account service', async () => { + const call = jest.fn().mockResolvedValue(undefined) + const client = {call} as unknown as Client jest.mocked(Notifications.getPermissionsAsync).mockResolvedValue({ granted: true, @@ -36,9 +34,12 @@ describe('unregisterPushToken', () => { data: 'device-token', }) - await unregisterPushToken([client], 'https://blacksky.app') + await unregisterPushToken([ + {client, service: 'https://blacksky.app', handle: 'alice.test'}, + ]) - expect(unregisterPush).toHaveBeenCalledWith( + expect(call).toHaveBeenCalledWith( + app.bsky.notification.unregisterPush, expect.objectContaining({ serviceDid: PUBLIC_APPVIEW_DID, token: 'device-token', diff --git a/src/state/__tests__/appview-fallback-probe.test.ts b/src/state/__tests__/appview-fallback-probe.test.ts index 28daee86e..d70abd640 100644 --- a/src/state/__tests__/appview-fallback-probe.test.ts +++ b/src/state/__tests__/appview-fallback-probe.test.ts @@ -1,5 +1,8 @@ -import {type Client} from '@atproto/lex' +import {type Client, XrpcResponseError} from '@atproto/lex' + +import {BLUESKY_APPVIEW_PINNED_OPTS} from '#/lib/constants' +import {app} from '#/lexicons' import { probeFallbackEligibility, resetProbeCacheForTesting, @@ -9,11 +12,16 @@ jest.mock('#/analytics/metrics', () => ({ metrics: {track: jest.fn()}, })) -function agentWith(getProfile: jest.Mock, did = 'did:plc:test123'): Client { - return { - session: {did}, - app: {bsky: {actor: {getProfile}}}, - } as unknown as AtpAgent +function clientWith(getProfile: jest.Mock, did = 'did:plc:test123'): Client { + return {did, call: getProfile} as unknown as Client +} + +function xrpcError(status: number, error: string) { + return new XrpcResponseError( + app.bsky.actor.getProfile.main, + new Response(null, {status}), + {encoding: 'application/json', body: {error, message: error}}, + ) } describe('probeFallbackEligibility', () => { @@ -22,24 +30,27 @@ describe('probeFallbackEligibility', () => { }) it('eligible when the fallback appview serves the profile', async () => { - const getProfile = jest.fn().mockResolvedValue({data: {}}) - expect(await probeFallbackEligibility(agentWith(getProfile))).toBe( + const getProfile = jest.fn().mockResolvedValue({}) + expect(await probeFallbackEligibility(clientWith(getProfile))).toBe( 'eligible', ) + expect(getProfile).toHaveBeenCalledWith( + app.bsky.actor.getProfile, + {actor: 'did:plc:test123'}, + BLUESKY_APPVIEW_PINNED_OPTS, + ) }) it.each([ - ['AccountTakedown error name', {error: 'AccountTakedown', status: 400}], - ['AccountDeactivated error name', {error: 'AccountDeactivated'}], - ['401 status', {status: 401}], - ['403 status', {status: 403}], - ['suspended message', {message: 'Account has been suspended'}], - ['taken down message', {message: 'this account was taken down'}], - ])('ineligible on %s', async (_name, errShape) => { - const getProfile = jest - .fn() - .mockRejectedValue(Object.assign(new Error(), errShape)) - expect(await probeFallbackEligibility(agentWith(getProfile))).toBe( + ['AccountTakedown error name', xrpcError(400, 'AccountTakedown')], + ['AccountDeactivated error name', xrpcError(400, 'AccountDeactivated')], + ['401 status', xrpcError(401, 'AuthenticationRequired')], + ['403 status', xrpcError(403, 'Forbidden')], + ['suspended message', new Error('Account has been suspended')], + ['taken down message', new Error('this account was taken down')], + ])('ineligible on %s', async (_name, error) => { + const getProfile = jest.fn().mockRejectedValue(error) + expect(await probeFallbackEligibility(clientWith(getProfile))).toBe( 'ineligible', ) }) @@ -48,16 +59,16 @@ describe('probeFallbackEligibility', () => { const getProfile = jest .fn() .mockRejectedValueOnce(new Error('Network request failed')) - .mockResolvedValueOnce({data: {}}) - const client = agentWith(getProfile) + .mockResolvedValueOnce({}) + const client = clientWith(getProfile) expect(await probeFallbackEligibility(client)).toBe('unknown') expect(await probeFallbackEligibility(client)).toBe('eligible') }) it('caches a definitive result per DID', async () => { - const getProfile = jest.fn().mockResolvedValue({data: {}}) - const client = agentWith(getProfile) + const getProfile = jest.fn().mockResolvedValue({}) + const client = clientWith(getProfile) await probeFallbackEligibility(client) await probeFallbackEligibility(client) @@ -67,11 +78,9 @@ describe('probeFallbackEligibility', () => { it('re-probes after the cache TTL expires', async () => { const getProfile = jest .fn() - .mockResolvedValueOnce({data: {}}) - .mockRejectedValueOnce( - Object.assign(new Error(), {error: 'AccountTakedown', status: 400}), - ) - const client = agentWith(getProfile) + .mockResolvedValueOnce({}) + .mockRejectedValueOnce(xrpcError(400, 'AccountTakedown')) + const client = clientWith(getProfile) const nowSpy = jest.spyOn(Date, 'now') nowSpy.mockReturnValue(1_000_000) @@ -86,10 +95,7 @@ describe('probeFallbackEligibility', () => { it('unknown without a session', async () => { const getProfile = jest.fn() - const client = { - session: undefined, - app: {bsky: {actor: {getProfile}}}, - } as unknown as AtpAgent + const client = {did: undefined, call: getProfile} as unknown as Client expect(await probeFallbackEligibility(client)).toBe('unknown') expect(getProfile).not.toHaveBeenCalled() }) diff --git a/src/state/__tests__/appview-fallback.test.ts b/src/state/__tests__/appview-fallback.test.ts index 513c67a66..23de9325c 100644 --- a/src/state/__tests__/appview-fallback.test.ts +++ b/src/state/__tests__/appview-fallback.test.ts @@ -1,4 +1,4 @@ -import {type Client} from '@atproto/lex' +import {type Agent} from '@atproto/lex' import {type QueryClient} from '@tanstack/react-query' import { @@ -6,85 +6,111 @@ import { BLUESKY_PROXY_HEADER, HOME_PROXY_HEADER, } from '#/lib/constants' +import {buildAppviewClient} from '#/state/session/clients' +import {app} from '#/lexicons' import { isFallbackActive, setFallbackActive, subscribe, } from '../appview-fallback' +jest.mock('#/analytics/metrics', () => ({metrics: {track: jest.fn()}})) +jest.mock('#/analytics/identifiers', () => ({ + getDeviceId: jest.fn(), + getSessionId: jest.fn(), +})) + function mocks() { - const configureProxy = jest.fn() const resetQueries = jest.fn().mockResolvedValue(undefined) return { - agent: {configureProxy} as unknown as BskyAgent, queryClient: {resetQueries} as unknown as QueryClient, - configureProxy, resetQueries, } } +function liveClient() { + const fetchHandler = jest.fn, [string, RequestInit]>(() => + Promise.resolve( + new Response( + JSON.stringify({did: 'did:plc:alice', handle: 'alice.test'}), + {headers: {'content-type': 'application/json'}}, + ), + ), + ) + const client = buildAppviewClient({ + did: 'did:plc:me', + fetchHandler, + } as unknown as Agent) + const proxyOf = async () => { + fetchHandler.mockClear() + await client.call(app.bsky.actor.getProfile, {actor: 'alice.test'}) + return new Headers(fetchHandler.mock.calls[0][1].headers).get( + 'atproto-proxy', + ) + } + return {proxyOf} +} + describe('appview fallback state', () => { afterEach(() => { - const {client, queryClient} = mocks() - setFallbackActive(false, client, queryClient) + setFallbackActive(false, mocks().queryClient) BLUESKY_PROXY_HEADER.set(HOME_PROXY_HEADER) }) - it('activating flips the global header, live client, and resets the cache', () => { - const {client, queryClient, configureProxy, resetQueries} = mocks() + it('activating flips the global header and resets the cache', () => { + const {queryClient, resetQueries} = mocks() - setFallbackActive(true, client, queryClient) + setFallbackActive(true, queryClient) expect(isFallbackActive()).toBe(true) expect(BLUESKY_PROXY_HEADER.get()).toBe(BLUESKY_FALLBACK_PROXY_HEADER) - expect(configureProxy).toHaveBeenCalledWith(BLUESKY_FALLBACK_PROXY_HEADER) expect(resetQueries).toHaveBeenCalledTimes(1) }) it('deactivating restores the home appview header', () => { - const first = mocks() - setFallbackActive(true, first.agent, first.queryClient) - - const second = mocks() - setFallbackActive(false, second.agent, second.queryClient) + setFallbackActive(true, mocks().queryClient) + setFallbackActive(false, mocks().queryClient) expect(isFallbackActive()).toBe(false) expect(BLUESKY_PROXY_HEADER.get()).toBe(HOME_PROXY_HEADER) - expect(second.configureProxy).toHaveBeenCalledWith(HOME_PROXY_HEADER) }) - it('setting the same value skips the reset but still aligns the client', () => { - const {client, queryClient, configureProxy, resetQueries} = mocks() + it('setting the same value skips the reset', () => { + const {queryClient, resetQueries} = mocks() - setFallbackActive(false, client, queryClient) + setFallbackActive(false, queryClient) - expect(configureProxy).toHaveBeenCalledWith(HOME_PROXY_HEADER) + expect(BLUESKY_PROXY_HEADER.get()).toBe(HOME_PROXY_HEADER) expect(resetQueries).not.toHaveBeenCalled() }) - it('a fresh client passed after activation gets the fallback header', () => { - const first = mocks() - setFallbackActive(true, first.agent, first.queryClient) + it('moves a live appview client with each flip', async () => { + const {proxyOf} = liveClient() + expect(await proxyOf()).toBe(HOME_PROXY_HEADER) - const second = mocks() - setFallbackActive(true, second.agent, second.queryClient) + setFallbackActive(true, mocks().queryClient) + expect(await proxyOf()).toBe(BLUESKY_FALLBACK_PROXY_HEADER) - expect(second.configureProxy).toHaveBeenCalledWith( - BLUESKY_FALLBACK_PROXY_HEADER, - ) - expect(second.resetQueries).not.toHaveBeenCalled() + setFallbackActive(false, mocks().queryClient) + expect(await proxyOf()).toBe(HOME_PROXY_HEADER) + }) + + it('a client built after activation targets the fallback appview', async () => { + setFallbackActive(true, mocks().queryClient) + + expect(await liveClient().proxyOf()).toBe(BLUESKY_FALLBACK_PROXY_HEADER) }) it('notifies subscribers on change and stops after unsubscribe', () => { - const {client, queryClient} = mocks() + const {queryClient} = mocks() const fn = jest.fn() const unsub = subscribe(fn) - setFallbackActive(true, client, queryClient) + setFallbackActive(true, queryClient) expect(fn).toHaveBeenCalledTimes(1) unsub() - setFallbackActive(false, client, queryClient) + setFallbackActive(false, queryClient) expect(fn).toHaveBeenCalledTimes(1) }) }) diff --git a/src/state/queries/__tests__/profile-enrichment.test.tsx b/src/state/queries/__tests__/profile-enrichment.test.tsx index e75fe287b..7a1db35e9 100644 --- a/src/state/queries/__tests__/profile-enrichment.test.tsx +++ b/src/state/queries/__tests__/profile-enrichment.test.tsx @@ -228,17 +228,17 @@ describe('useProfileEnrichment', () => { ), ) - const client = new BskyAgent({service: 'https://pds.test'}) - client.sessionManager.session = { + // The client a feed API holds carries a profile-shaped session object. + const session = { did: ME, handle: 'me.test', accessJwt: 'a', refreshJwt: 'r', active: true, } - const session = client.sessionManager.session + const held = {did: ME, agent: {session}} const sessionBefore = {...session} - const api = new FollowingFeedAPI({client}) + const api = new FollowingFeedAPI({client: held as unknown as Client}) type FeedPage = { api: FollowingFeedAPI @@ -276,8 +276,8 @@ describe('useProfileEnrichment', () => { expect(data.pageParams[1]?.api).toBe(api) expect(typeof data.pages[1].api.peekLatest).toBe('function') expect(typeof data.pages[1].api.fetch).toBe('function') - expect(client.sessionManager.session).toBe(session) - expect(client.sessionManager.session).toEqual(sessionBefore) + expect(held.agent.session).toBe(session) + expect(held.agent.session).toEqual(sessionBefore) return data } diff --git a/src/state/queries/__tests__/space-engagement-routing.test.ts b/src/state/queries/__tests__/space-engagement-routing.test.ts index 47920ad98..f804ce5c6 100644 --- a/src/state/queries/__tests__/space-engagement-routing.test.ts +++ b/src/state/queries/__tests__/space-engagement-routing.test.ts @@ -6,10 +6,12 @@ jest.mock('#/lib/api/community', () => ({ getSpacePostLikes: (...args: unknown[]) => mockGetSpacePostLikes(...args), getSpacePostQuotes: (...args: unknown[]) => mockGetSpacePostQuotes(...args), })) -jest.mock('#/state/session', () => ({useAgent: jest.fn()})) +jest.mock('#/state/session', () => ({useAppviewClient: jest.fn()})) import {type Client} from '@atproto/lex' -import {fetchLikedByPage, fetchLikedBySample} from '../post-liked-by' + +import {app} from '#/lexicons' +import {fetchLikedByPage} from '../post-liked-by' import {fetchPostQuotesPage} from '../post-quotes' import {fetchRepostedByPage} from '../post-reposted-by' @@ -18,23 +20,22 @@ const SPACE_POST = `${SPACE}/did:plc:alice/app.bsky.feed.post/3kpost` const PUBLIC_POST = 'at://did:plc:alice/app.bsky.feed.post/3kpost' const LEGACY_POST = 'at://did:plc:alice/community.blacksky.feed.post/3kpost' -function mockAgent() { - const getLikes = jest.fn().mockResolvedValue({ - data: {uri: PUBLIC_POST, likes: []}, - }) - const getQuotes = jest.fn().mockResolvedValue({ - data: {uri: PUBLIC_POST, posts: []}, - }) - const getRepostedBy = jest.fn().mockResolvedValue({ - data: {uri: PUBLIC_POST, repostedBy: []}, - }) +function mockClient() { + const getLikes = jest.fn().mockResolvedValue({uri: PUBLIC_POST, likes: []}) + const getQuotes = jest.fn().mockResolvedValue({uri: PUBLIC_POST, posts: []}) + const getRepostedBy = jest + .fn() + .mockResolvedValue({uri: PUBLIC_POST, repostedBy: []}) mockGetSpacePostLikes.mockResolvedValue({uri: SPACE_POST, likes: []}) mockGetSpacePostQuotes.mockResolvedValue({uri: SPACE_POST, posts: []}) const client = { - getLikes, - getRepostedBy, - api: {app: {bsky: {feed: {getQuotes}}}}, - } as unknown as BskyAgent + call: (method: unknown, params: unknown) => { + if (method === app.bsky.feed.getLikes) return getLikes(params) + if (method === app.bsky.feed.getQuotes) return getQuotes(params) + if (method === app.bsky.feed.getRepostedBy) return getRepostedBy(params) + throw new Error('unexpected call') + }, + } as unknown as Client return {client, getLikes, getQuotes, getRepostedBy} } @@ -46,7 +47,7 @@ describe('post engagement routing', () => { it.each([PUBLIC_POST, LEGACY_POST])( 'keeps likes for %s on the standard endpoint', async uri => { - const {client, getLikes} = mockAgent() + const {client, getLikes} = mockClient() await fetchLikedByPage(client, uri, 'next') @@ -62,9 +63,9 @@ describe('post engagement routing', () => { it.each([PUBLIC_POST, LEGACY_POST])( 'keeps quotes for %s on the standard endpoint', async uri => { - const {client, getQuotes} = mockAgent() + const {client, getQuotes} = mockClient() - await fetchPostQuotesPage(client, uri, 'next') + await fetchPostQuotesPage(client, uri, {cursor: 'next'}) expect(getQuotes).toHaveBeenCalledWith({ uri, @@ -76,7 +77,7 @@ describe('post engagement routing', () => { ) it('uses only the permission-aware endpoints for space engagement', async () => { - const {client, getLikes, getQuotes} = mockAgent() + const {client, getLikes, getQuotes} = mockClient() await fetchLikedByPage(client, SPACE_POST) await fetchPostQuotesPage(client, SPACE_POST) @@ -95,31 +96,8 @@ describe('post engagement routing', () => { }) }) - it('samples known likers of a space post from the permission-aware endpoint', async () => { - const {client, getLikes} = mockAgent() - - await fetchLikedBySample(client, SPACE_POST) - - expect(getLikes).not.toHaveBeenCalled() - expect(mockGetSpacePostLikes).toHaveBeenCalledTimes(1) - expect(mockGetSpacePostLikes).toHaveBeenCalledWith(client, { - uri: SPACE_POST, - limit: 100, - }) - }) - - it('samples known likers of a public post from the standard endpoint', async () => { - const {client, getLikes} = mockAgent() - - await fetchLikedBySample(client, PUBLIC_POST) - - expect(mockGetSpacePostLikes).not.toHaveBeenCalled() - expect(getLikes).toHaveBeenCalledTimes(1) - expect(getLikes).toHaveBeenCalledWith({uri: PUBLIC_POST, limit: 100}) - }) - it('never calls the standard repost endpoint for a space URI', async () => { - const {client, getRepostedBy} = mockAgent() + const {client, getRepostedBy} = mockClient() await expect(fetchRepostedByPage(client, SPACE_POST)).rejects.toThrow( 'Reposts are not supported for private space posts', diff --git a/src/view/com/composer/drafts/state/__tests__/api-event.test.ts b/src/view/com/composer/drafts/state/__tests__/api-event.test.ts index a90c0b167..3f534f0cf 100644 --- a/src/view/com/composer/drafts/state/__tests__/api-event.test.ts +++ b/src/view/com/composer/drafts/state/__tests__/api-event.test.ts @@ -1,4 +1,3 @@ - import {RichText} from '@bsky/sdk/richtext' import {type app} from '#/lexicons' import { @@ -11,6 +10,7 @@ import { draftToComposerPosts, draftViewToSummary, } from '../api' +import {type LinkResolvers} from '#/lib/api/resolve' jest.mock('../storage', () => ({ mediaExists: jest.fn(() => true), @@ -29,7 +29,6 @@ jest.mock('#/lib/media/manip', () => ({getImageDim: jest.fn()})) jest.mock('#/lib/media/video/util', () => ({mimeToExt: jest.fn(() => 'mp4')})) jest.mock('#/lib/deviceName', () => ({getDeviceName: () => 'Test device'})) jest.mock('#/analytics/identifiers', () => ({getDeviceId: () => 'device-1'})) -jest.mock('#/state/session/agent', () => ({createPublicAgent: jest.fn()})) jest.mock('#/lib/api/resolve', () => ({resolveLink: jest.fn()})) jest.mock('#/state/queries/threadgate/util', () => ({ threadgateAllowUISettingToAllowRecordValue: jest.fn(() => undefined), @@ -39,6 +38,8 @@ jest.mock('#/view/com/composer/state/composer', () => ({ LEGACY_IMAGES_EMBED_MAX: 4, })) +const clients = {} as LinkResolvers + const EVENT_KEY = 'communityBlackskyEvent' const event: EventDraft = { @@ -82,7 +83,9 @@ function state(posts: PostDraft[]): ComposerState { } } -function draftPost(extra: Record): app.bsky.draft.defs.DraftPost { +function draftPost( + extra: Record, +): app.bsky.draft.defs.DraftPost { return { $type: 'app.bsky.draft.defs#draftPost', text: 'hello', @@ -90,23 +93,29 @@ function draftPost(extra: Record): app.bsky.draft.defs.DraftPos } } -function draftOf(posts: app.bsky.draft.defs.DraftPost[]): app.bsky.draft.defs.Draft { +function draftOf( + posts: app.bsky.draft.defs.DraftPost[], +): app.bsky.draft.defs.Draft { return {$type: 'app.bsky.draft.defs#draft', posts} } describe('draft events', () => { it('saves the event as an extra property on the draft post', async () => { - const {draft} = await composerStateToDraft(state([post({event})])) + const {draft} = await composerStateToDraft(clients, state([post({event})])) expect(savedEvent(draft)).toStrictEqual(event) }) it('omits the property when there is no event', async () => { - const {draft} = await composerStateToDraft(state([post({}, 'text')])) + const {draft} = await composerStateToDraft( + clients, + state([post({}, 'text')]), + ) expect(EVENT_KEY in draft.posts[0]).toBe(false) }) it("keeps a link's image but drops a picked photo, which lives only on this device", async () => { const withLink = await composerStateToDraft( + clients, state([post({event: {...event, cover: {url: 'https://x.test/og.jpg'}}})]), ) expect(savedEvent(withLink.draft)).toMatchObject({ @@ -114,6 +123,7 @@ describe('draft events', () => { }) const withPhoto = await composerStateToDraft( + clients, state([ post({ event: { @@ -133,6 +143,7 @@ describe('draft events', () => { it('round-trips an event through save and restore', async () => { const {draft} = await composerStateToDraft( + clients, state([post({event: {...event, coverRemoved: true}}, 'come')]), ) const {posts} = await draftToComposerPosts(asStored(draft), new Map()) diff --git a/src/view/com/composer/drafts/state/__tests__/api-poll.test.ts b/src/view/com/composer/drafts/state/__tests__/api-poll.test.ts index 825ee3fd8..7c80331c6 100644 --- a/src/view/com/composer/drafts/state/__tests__/api-poll.test.ts +++ b/src/view/com/composer/drafts/state/__tests__/api-poll.test.ts @@ -1,4 +1,3 @@ - import {RichText} from '@bsky/sdk/richtext' import {type app} from '#/lexicons' import {type AssemblyRef} from '#/lib/api/poll' @@ -11,6 +10,7 @@ import { draftToComposerPosts, draftViewToSummary, } from '../api' +import {type LinkResolvers} from '#/lib/api/resolve' jest.mock('../storage', () => ({ mediaExists: jest.fn(() => true), @@ -29,7 +29,6 @@ jest.mock('#/lib/media/manip', () => ({getImageDim: jest.fn()})) jest.mock('#/lib/media/video/util', () => ({mimeToExt: jest.fn(() => 'mp4')})) jest.mock('#/lib/deviceName', () => ({getDeviceName: () => 'Test device'})) jest.mock('#/analytics/identifiers', () => ({getDeviceId: () => 'device-1'})) -jest.mock('#/state/session/agent', () => ({createPublicAgent: jest.fn()})) jest.mock('#/lib/api/resolve', () => ({resolveLink: jest.fn()})) jest.mock('#/state/queries/threadgate/util', () => ({ threadgateAllowUISettingToAllowRecordValue: jest.fn(() => undefined), @@ -39,6 +38,8 @@ jest.mock('#/view/com/composer/state/composer', () => ({ LEGACY_IMAGES_EMBED_MAX: 4, })) +const clients = {} as LinkResolvers + const POLL_KEY = 'communityBlackskyPoll' const pendingRef: AssemblyRef = { @@ -85,7 +86,9 @@ function state(posts: PostDraft[]): ComposerState { } } -function draftPost(extra: Record): app.bsky.draft.defs.DraftPost { +function draftPost( + extra: Record, +): app.bsky.draft.defs.DraftPost { return { $type: 'app.bsky.draft.defs#draftPost', text: 'hello', @@ -93,13 +96,16 @@ function draftPost(extra: Record): app.bsky.draft.defs.DraftPos } } -function draftOf(posts: app.bsky.draft.defs.DraftPost[]): app.bsky.draft.defs.Draft { +function draftOf( + posts: app.bsky.draft.defs.DraftPost[], +): app.bsky.draft.defs.Draft { return {$type: 'app.bsky.draft.defs#draft', posts} } describe('draft polls', () => { it('serialises the poll as an extra property on the draft post', async () => { const {draft} = await composerStateToDraft( + clients, state([post({poll: {statements: ['one', '']}}, 'question')]), ) expect(savedPoll(draft)).toStrictEqual({statements: ['one', '']}) @@ -107,6 +113,7 @@ describe('draft polls', () => { it('serialises the assembly reference with the statements', async () => { const {draft} = await composerStateToDraft( + clients, state([ post( {poll: {statements: ['first', 'second'], assembly: createdRef}}, @@ -128,6 +135,7 @@ describe('draft polls', () => { it('serialises the poll of the post that has one', async () => { const {draft} = await composerStateToDraft( + clients, state([ post({}, 'lead'), post({poll: {statements: ['first'], assembly: pendingRef}}, 'question'), @@ -141,7 +149,10 @@ describe('draft polls', () => { }) it('omits the property when there is no poll', async () => { - const {draft} = await composerStateToDraft(state([post({}, 'text only')])) + const {draft} = await composerStateToDraft( + clients, + state([post({}, 'text only')]), + ) expect(POLL_KEY in draft.posts[0]).toBe(false) }) @@ -156,6 +167,7 @@ describe('draft polls', () => { it('round-trips a poll through save and restore', async () => { const {draft} = await composerStateToDraft( + clients, state([post({poll: {statements: ['first', 'second']}}, 'question')]), ) const {posts} = await draftToComposerPosts(asStored(draft), new Map()) @@ -169,6 +181,7 @@ describe('draft polls', () => { {kind: 'an assembly that is still being created', assembly: pendingRef}, ])('round-trips the reference to $kind', async ({assembly}) => { const {draft} = await composerStateToDraft( + clients, state([ post({poll: {statements: ['first', 'second'], assembly}}, 'question'), ]), @@ -187,6 +200,7 @@ describe('draft polls', () => { it('round-trips a saved reference through a second save', async () => { const first = await composerStateToDraft( + clients, state([ post( {poll: {statements: ['first', 'second'], assembly: pendingRef}}, @@ -198,7 +212,7 @@ describe('draft polls', () => { asStored(first.draft), new Map(), ) - const second = await composerStateToDraft(state(restored.posts)) + const second = await composerStateToDraft(clients, state(restored.posts)) expect(asStored(second.draft).posts[0]).toHaveProperty(POLL_KEY, { statements: ['first', 'second'], @@ -316,6 +330,7 @@ describe('draft polls', () => { String(index).repeat(400), ) const {draft} = await composerStateToDraft( + clients, state([ post({poll: {statements, assembly: createdRef}}, 'question'), ...Array.from({length: 31}, () => post({}, text)), diff --git a/src/view/shell/__tests__/Composer-context.test.tsx b/src/view/shell/__tests__/Composer-context.test.tsx index 3d3a2f80f..fb2b11b5a 100644 --- a/src/view/shell/__tests__/Composer-context.test.tsx +++ b/src/view/shell/__tests__/Composer-context.test.tsx @@ -15,14 +15,11 @@ jest.mock('#/components/Tooltip', () => ({ })) jest.mock('#/alf', () => ({ atoms: {absolute: {}, inset_0: {}}, + BreakpointWidthContext: jest + .requireActual('react') + .createContext(undefined), useTheme: () => ({name: 'light', atoms: {bg: {}}}), })) -jest.mock('react-native-edge-to-edge', () => ({ - SystemBars: { - pushStackEntry: jest.fn(() => ({})), - popStackEntry: jest.fn(), - }, -})) jest.mock('react-native-reanimated', () => { const {View} = require('react-native') const animation = {duration: () => animation, easing: () => animation} -- knotmirror 0.0.1