Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 65 additions & 12 deletions src/renderer/hooks/useLogins.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,24 @@ import { useAccountsStore } from '../stores';
import type { ClientID, Token } from '../types';
import type { DeviceFlowSession } from '../utils/auth/types';

import { notificationsKeys } from '../utils/api/queryKeys';
import { getAdapter } from '../utils/forges/registry';
import { useLogins } from './useLogins';

// Exercise the real hook implementation (globally mocked in vitest.setup)
vi.unmock('./useLogins');

const createWrapper = () => {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
},
const renderLoginsHook = (
queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
}),
) =>
renderHook(() => useLogins(), {
wrapper: ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
),
});

return ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
};

const renderLoginsHook = () => renderHook(() => useLogins(), { wrapper: createWrapper() });

describe('renderer/hooks/useLogins.ts', () => {
const removeAccountNotificationsMock = vi.fn();
let createAccountSpy: ReturnType<typeof vi.spyOn>;
Expand All @@ -54,6 +52,61 @@ describe('renderer/hooks/useLogins.ts', () => {
removeAccountSpy.mockClear();
});

it.each<{ name: string; login: (logins: ReturnType<typeof useLogins>) => Promise<void> }>([
{
name: 'GitHub CLI',
login: (logins) => logins.loginWithCli('github', Constants.GITHUB_HOSTNAME),
},
{
name: 'OAuth device flow',
login: (logins) =>
logins.loginWithDeviceFlowComplete('github', 'token' as Token, Constants.GITHUB_HOSTNAME),
},
{
name: 'personal access token',
login: (logins) =>
logins.loginWithPersonalAccessToken({
forge: 'github',
hostname: Constants.GITHUB_HOSTNAME,
token: 'token' as Token,
}),
},
])(
'completes $name login after saving the account without waiting for notifications',
async ({ login }) => {
const saved = Promise.withResolvers<void>();
const refreshed = Promise.withResolvers<void>();
const queryClient = new QueryClient();
const invalidate = vi
.spyOn(queryClient, 'invalidateQueries')
.mockReturnValue(refreshed.promise);
createAccountSpy.mockReturnValue(saved.promise);
const github = getAdapter('github');
vi.spyOn(github.cliAuth!, 'resolveToken').mockResolvedValue('token' as Token);
vi.spyOn(github.accountOps, 'fetchAuthenticatedUser').mockResolvedValue({
user: { ...mockGitHubCloudAccount.user!, avatar: mockGitHubCloudAccount.user!.avatar! },
});

const { result } = renderLoginsHook(queryClient);
const onComplete = vi.fn();
const loginPromise = login(result.current).then(onComplete);

try {
await vi.waitFor(() => expect(createAccountSpy).toHaveBeenCalled());
expect(invalidate).not.toHaveBeenCalled();
expect(onComplete).not.toHaveBeenCalled();

saved.resolve();
await vi.waitFor(() => expect(onComplete).toHaveBeenCalledOnce());
expect(invalidate).toHaveBeenCalledWith({ queryKey: notificationsKeys.all });
} finally {
saved.resolve();
refreshed.resolve();
await loginPromise;
}
},
);

it('loginWithDeviceFlowStart delegates to the forge adapter', async () => {
const adapter = getAdapter('github');
const startSpy = vi.spyOn(adapter.deviceFlow!, 'start').mockImplementation(vi.fn());
Expand Down
18 changes: 11 additions & 7 deletions src/renderer/hooks/useLogins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,18 +50,22 @@ export const useLogins = (): LoginsState => {

const { removeAccountNotifications } = useNotificationActions();

const refreshNotificationsInBackground = useCallback(() => {
// Re-authentication can keep the same query key, so invalidate it even
// when the account list has not changed. The inbox handles fetching state.
void queryClient.invalidateQueries({ queryKey: notificationsKeys.all });
}, [queryClient]);

/**
* Create (or update) an account, then refetch notifications. Re-authenticating
* an existing account keeps the same account identity, so the notifications
* query key does not change and the cache must be invalidated explicitly.
* Create (or update) an account before starting the notification refresh.
*/
const createAccount = useCallback(
async (...args: Parameters<typeof createAccountInStore>) => {
await createAccountInStore(...args);

await queryClient.invalidateQueries({ queryKey: notificationsKeys.all });
refreshNotificationsInBackground();
},
[createAccountInStore, queryClient],
[createAccountInStore, refreshNotificationsInBackground],
);

/**
Expand Down Expand Up @@ -138,9 +142,9 @@ export const useLogins = (): LoginsState => {

existingAccounts.forEach((account) => removeAccountNotifications(account));

await queryClient.invalidateQueries({ queryKey: notificationsKeys.all });
refreshNotificationsInBackground();
},
[createAccountInStore, queryClient, removeAccountNotifications],
[createAccountInStore, refreshNotificationsInBackground, removeAccountNotifications],
);

/**
Expand Down
Loading