Files
supabase/apps/studio/components/interfaces/MCP/Secrets/useSecretRequest.test.ts
Joshen Lim 60b51d74d5 Audit existing unit tests + Remove redundant ones (#52215)
## Context

_TLDR: Changes here speeds up unit tests on CI from ~14 minutes to ~3
minutes_ 😂
_TLDR 2: The file changes are solely only test files +
`studio-unit-tests.yml`_

We've currently got a lot of unit tests in the repository which while
great for coverage, hasn't been ideally written. There's a lot of
redundancy + overly specific tests that break easily, and our current
unit test takes about 15 minutes to run in the GHA per PR. Hence am
doing a audit clean up of all existing unit tests in the studio repo.

## Changes involved
- `.test.ts` files now run in `node`, `.test.tsx` in `jsdom`
- jsdom costs about 1s of setup per file. A `.ts` test that needs the
DOM opts in with `// @vitest-environment jsdom` (46 files do).
- Removed redundant and over-specific tests
- Duplicates are merged into `test.each`. Tests that only covered
libraries, existed for coverage, or asserted class names and snapshots
are deleted. 19 files are merged into a sibling or deleted.
- Fixed about 15 tests that couldn't fail 
- Examples: unawaited assertions, fixtures equal to the default, and a
`semverGte` test calling `semverLte`.
- Sped up the slowest files 
- Real sleeps are replaced with fake timers, `user.type` with paste, and
Radix option queries are scoped to the open listbox. For example,
`RestoringState` went from 18s to 0.3s and
`useTableEditorFiltersSort.navigation` from 20s to 3s.
- These ^ already shave down the unit tests time from 14 mins to 9 mins,
but am also sharding unit tests across 4 jobs to increase speed up
further which then shaves down time to 3 mins now
2026-10-23 18:51:27 +08:00

144 lines
4.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// @vitest-environment jsdom
import { act, waitFor } from '@testing-library/react'
import { delay, HttpResponse } from 'msw'
import { beforeEach, describe, expect, it } from 'vitest'
import type { SecretsParams } from './McpSecrets.params'
import { useSecretRequest } from './useSecretRequest'
import type { components } from '@/data/api'
import { customRenderHook } from '@/tests/lib/custom-render'
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
const REF_A = 'aaaaaaaaaaaaaaaaaaaa'
const NAME_A = 'OPENAI_API_KEY'
const NAME_B = 'RESEND_API_KEY'
const paramsFor = (ref: string, name: string): SecretsParams => ({
ref,
name,
dev: { state: undefined },
})
const WRITE_DELAY_MS = 50
const PROJECT: components['schemas']['ProjectDetailResponse_Output'] = {
cloud_provider: 'AWS',
db_host: 'db.example.supabase.co',
high_availability: false,
id: 1,
inserted_at: '2026-01-01T00:00:00Z',
integration_source: null,
is_branch_enabled: false,
is_physical_backups_enabled: false,
name: 'acme-production',
organization_id: 1,
ref: REF_A,
region: 'us-east-1',
restUrl: 'https://example.supabase.co/rest/v1/',
status: 'ACTIVE_HEALTHY',
subscription_id: 'sub_1',
updated_at: '2026-01-01T00:00:00Z',
connectionString: '',
}
let writtenNames: string[] = []
beforeEach(() => {
writtenNames = []
addAPIMock({ method: 'get', path: '/platform/projects/:ref', response: PROJECT })
addAPIMock({ method: 'get', path: '/v1/projects/:ref/secrets', response: [] })
addAPIMock({
method: 'post',
path: '/v1/projects/:ref/secrets',
response: async ({ request }) => {
const body = (await request.json()) as { name: string }[]
writtenNames.push(...body.map((secret) => secret.name))
await delay(WRITE_DELAY_MS)
return HttpResponse.json([])
},
})
})
describe('useSecretRequest', () => {
it('reports a stored outcome for the request that was actually written', async () => {
const { result } = customRenderHook(() => useSecretRequest(paramsFor(REF_A, NAME_A)))
await waitFor(() => expect(result.current.state.status).toBe('form'))
act(() => result.current.saveSecret('sk-value'))
await waitFor(() => expect(result.current.state.status).toBe('stored'))
expect(writtenNames).toEqual([NAME_A])
})
it('does not offer the form when the existing secrets cannot be read', async () => {
// Without the secrets list there is no way to know an overwrite is about to
// happen, so the form would be missing its warning.
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/secrets',
response: () => HttpResponse.json<APIErrorBody>({ message: 'nope' }, { status: 500 }),
})
const { result } = customRenderHook(() => useSecretRequest(paramsFor(REF_A, NAME_A)))
await waitFor(() => expect(result.current.state.status).toBe('error'))
expect(writtenNames).toEqual([])
})
it('does not attribute request A’s settled write to request B', async () => {
let params = paramsFor(REF_A, NAME_A)
const { result, rerender } = customRenderHook(() => useSecretRequest(params))
await waitFor(() => expect(result.current.state.status).toBe('form'))
act(() => result.current.saveSecret('sk-belongs-to-a'))
params = paramsFor(REF_A, NAME_B)
rerender()
await waitFor(() => {
const { state } = result.current
expect(state.status === 'form' && state.request.keyName).toBe(NAME_B)
})
await new Promise((resolve) => setTimeout(resolve, WRITE_DELAY_MS * 3))
expect(result.current.state.status).toBe('form')
expect(writtenNames).toEqual([NAME_A])
})
it('does not carry a cancellation from request A onto request B', async () => {
let params = paramsFor(REF_A, NAME_A)
const { result, rerender } = customRenderHook(() => useSecretRequest(params))
await waitFor(() => expect(result.current.state.status).toBe('form'))
act(() => result.current.cancelRequest())
expect(result.current.state.status).toBe('cancelled')
params = paramsFor(REF_A, NAME_B)
rerender()
await waitFor(() => expect(result.current.state.status).toBe('form'))
})
it('still shows A’s outcome if the user navigates back to A', async () => {
let params = paramsFor(REF_A, NAME_A)
const { result, rerender } = customRenderHook(() => useSecretRequest(params))
await waitFor(() => expect(result.current.state.status).toBe('form'))
act(() => result.current.cancelRequest())
params = paramsFor(REF_A, NAME_B)
rerender()
await waitFor(() => expect(result.current.state.status).toBe('form'))
params = paramsFor(REF_A, NAME_A)
rerender()
await waitFor(() => expect(result.current.state.status).toBe('cancelled'))
})
})