Files
supabase/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.test.tsx
T
1966209483 chore(deps): upgrade vitest to v5 (#49994)
Upgrades Vitest from 4.1.4 to 5.0.0 across the monorepo, fixes the
handful of things v5 turned into hard errors, and drops the
`vi.clearAllMocks()` boilerplate that v5's `clearMocks` default makes
redundant.

**Changed:**
- `vitest`, `@vitest/ui`, `@vitest/coverage-v8` 4.1.4 → 5.0.0 (catalog)
- `vi.mock` calls that lived inside `beforeAll`/`beforeEach`/test bodies
moved to module scope (v5 throws on nested calls). Affects the Studio
and docs setup files and four Studio tests.
- `detectBrowser` test restores `navigator` via `vi.unstubAllGlobals()`
instead of assigning `global.navigator`, which now reaches jsdom's
getter-only property.
- `RowEditor.utils.test.ts` restores its `JSON.stringify` spy. It used
to leak a throwing mock for the rest of the file, which v5's coverage
provider now trips over. A later test in the same file had been
asserting the leak's side effect (valid JSON reported as invalid) and
now asserts the correct behavior.
- `@testing-library/jest-dom` 6.6 → 7.0.1. Its vitest type augmentation
resolves through a peer now, so it lands on each package's own `vitest`
instead of whichever copy pnpm hoisted. Fixes `toBeInTheDocument` type
errors in dev-tools after the reshuffle.
- `@testing-library/react` 16.0.0 → 16.3.3 for the React 19 peer range.
- `vite: catalog:` added to dev-tools, www, and common. Without it they
resolved a newer vite than the catalog pin, which forked a second vitest
instance in the lockfile. There's now one.
- ai-commands custom matcher types use v5's `Matchers<R, T>` form.
- 110 test files: `vi.clearAllMocks()` removed from
`beforeEach`/`afterEach` hooks, along with hooks that only did that and
the imports they left unused. Calls that also reset/restore mocks are
untouched. Second commit, mechanical.

**Added:**
- `.vitest/` to the root gitignore (v5 writes JSON/JUnit/HTML reporter
output there)

**Removed:**
- `vite-tsconfig-paths` catalog entry and deps. Vitest 5 resolves
tsconfig paths itself.

Release-age note: this sat in draft with a temporary
`minimumReleaseAgeExclude` entry for `vitest` and `@vitest/*` while
5.0.0 was inside the workspace's 3-day `minimumReleaseAge` window. That
window has closed, so the exclusion is gone and nothing bypasses the
release-age gate.

**Perf** (local, medians of 3 runs, same machine):

| Suite | v4.1.4 | v5.0.0 |
|---|---|---|
| studio | 144.1s | 141.7s (-2%) |
| studio `--coverage` | 156.9s | 146.4s (-7%) |
| ui-patterns | 6.27s | 5.07s (-19%) |
| ui `--coverage` | 3.35s | 2.14s (-36%) |
| www | 0.89s | 0.47s (-47%) |

Studio is dominated by jsdom environment setup per file, which v5
doesn't change. `vitest doctor` recommends keeping the current pool
config: the vm pools and `isolate: false` all break tests.

## To test

- `pnpm install --frozen-lockfile` succeeds with no
`minimumReleaseAgeExclude` entry for vitest.
- CI: Studio unit tests, ui, ui-patterns, www, docs, and typecheck/lint
should all be green. The lint ratchet was checked locally: warning
counts on touched Studio files are identical to master.
- `pnpm test:studio` locally passes with coverage (588 files, 6240
tests).
- Open a Studio test that uses `toBeInTheDocument` in your editor and
confirm no type errors on jest-dom matchers, in Studio and in
`packages/dev-tools`.
- Known pre-existing failures unrelated to this PR: one dev-tools test
(`getEventCountBadge` capped pill) fails on master too.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

## Tests
- Improved test coverage for JSON validation and mobile navigation
behavior.
- Updated test setup, cleanup, environment configuration, and matcher
support across application and shared package suites.
- Removed obsolete coverage for alternate MCP transport selection.

## Chores
- Streamlined TypeScript path resolution and Vitest reporter output
handling.
- Updated testing libraries and Vitest tooling across documentation,
Studio, website, and shared packages.
- Added Vitest reporter output to ignored files.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2026-09-10 16:45:54 +08:00

293 lines
9.4 KiB
TypeScript

import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { toast } from 'sonner'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { InviteMemberButton } from '@/components/interfaces/Organization/TeamSettings/InviteMemberButton'
import { customRender } from '@/tests/lib/custom-render'
vi.mock('sonner', () => ({
toast: { success: vi.fn(), error: vi.fn() },
}))
vi.mock('common', async (importOriginal) => {
const actual = (await importOriginal()) as typeof import('common')
return { ...actual, useParams: () => ({ slug: 'test-org' }) }
})
vi.mock('@/lib/profile', () => ({
useProfile: () => ({ profile: { id: 1, gotrue_id: 'user-1' } }),
}))
vi.mock('@/hooks/misc/useSelectedOrganization', () => ({
useSelectedOrganizationQuery: () => ({
data: { id: 1, slug: 'test-org', name: 'Test Org' },
}),
}))
vi.mock('@/hooks/misc/useCheckPermissions', () => ({
useGetPermissions: () => ({ permissions: [], organizationSlug: 'test-org' }),
doPermissionsCheck: () => true,
useAsyncCheckPermissions: () => ({ can: true, isSuccess: true }),
}))
vi.mock('@/hooks/misc/useIsFeatureEnabled', () => ({
useIsFeatureEnabled: () => ({ organizationMembersCreate: true }),
}))
vi.mock('@/data/organizations/organization-members-query', () => ({
useOrganizationMembersQuery: () => ({
data: [
{
gotrue_id: 'user-1',
primary_email: 'me@example.com',
role_ids: [1],
},
{
gotrue_id: 'existing-user',
primary_email: 'existing@example.com',
role_ids: [1],
},
],
}),
}))
const mockRoles = {
org_scoped_roles: [
{ id: 4, name: 'Owner', description: null },
{ id: 3, name: 'Administrator', description: null },
{ id: 1, name: 'Developer', description: null },
{ id: 2, name: 'Read-only', description: null },
],
}
vi.mock('@/data/organization-members/organization-roles-query', () => ({
useOrganizationRolesV2Query: () => ({ data: mockRoles, isSuccess: true }),
}))
vi.mock('@/data/sso/sso-config-query', () => ({
useOrgSSOConfigQuery: () => ({ data: null }),
}))
vi.mock('@/data/subscriptions/org-subscription-query', () => ({
useHasAccessToProjectLevelPermissions: () => false,
}))
vi.mock('@/hooks/misc/useCheckEntitlements', () => ({
useCheckEntitlements: () => ({ hasAccess: false }),
}))
vi.mock('@/components/interfaces/Organization/TeamSettings/TeamSettings.utils', () => ({
useGetRolesManagementPermissions: () => ({
rolesAddable: [1, 2, 3, 4],
rolesRemovable: [1, 2, 3, 4],
}),
}))
const mockInvite = vi.fn().mockResolvedValue({ succeeded: [], failed: [] })
vi.mock('@/data/organization-members/organization-invitation-create-mutation', () => ({
useOrganizationCreateInvitationMutation: () => ({
mutateAsync: mockInvite,
isPending: false,
}),
}))
vi.mock('@/hooks/ui/useConfirmOnClose', () => ({
useConfirmOnClose: ({ onClose }: { checkIsDirty: () => boolean; onClose: () => void }) => ({
confirmOnClose: onClose,
handleOpenChange: (open: boolean) => {
if (!open) onClose()
},
modalProps: { visible: false, onClose, onCancel: vi.fn() },
}),
}))
// Helpers
async function openDialog() {
await userEvent.click(screen.getByRole('button', { name: /invite members/i }))
return screen.findByRole('dialog')
}
async function submitForm(emailValue: string) {
await openDialog()
fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {
target: { value: emailValue },
})
fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))
}
// Tests
describe('InviteMemberButton', () => {
beforeEach(() => {
mockInvite.mockResolvedValue({ succeeded: [], failed: [] })
})
it('renders an enabled Invite members button', () => {
customRender(<InviteMemberButton />)
expect(screen.getByRole('button', { name: /invite members/i })).toBeEnabled()
})
it('opens the invite dialog when the button is clicked', async () => {
customRender(<InviteMemberButton />)
await openDialog()
expect(screen.getByRole('dialog')).toBeInTheDocument()
expect(screen.getByText('Invite team members')).toBeInTheDocument()
})
it('renders a stacked radio option with permission guidance for each role', async () => {
customRender(<InviteMemberButton />)
await openDialog()
expect(screen.getAllByRole('radio')).toHaveLength(4)
expect(screen.getByRole('link', { name: 'roles and permissions' })).toHaveAttribute(
'href',
'https://supabase.com/docs/guides/platform/access-control'
)
expect(
screen.getByText(
'Full access, including deleting the organization and transferring or deleting projects.'
)
).toBeInTheDocument()
expect(
screen.getByText(
'Manage members, billing, and project settings, including deleting projects. Cannot manage organization settings or owners.'
)
).toBeInTheDocument()
expect(
screen.getByText(
'Manage project content, including deleting data, users, files, and Edge Functions. Cannot change settings or delete projects.'
)
).toBeInTheDocument()
expect(
screen.getByText(
'View resources without modifying or deleting them. SQL Editor access is limited to SELECT queries.'
)
).toBeInTheDocument()
})
it('calls the mutation with a single email in an array', async () => {
customRender(<InviteMemberButton />)
await submitForm('new@example.com')
await waitFor(() => {
expect(mockInvite).toHaveBeenCalledWith(
expect.objectContaining({ emails: ['new@example.com'] })
)
})
})
it('calls the mutation with multiple emails parsed from a comma-separated input', async () => {
customRender(<InviteMemberButton />)
await submitForm('alice@example.com, bob@example.com, carol@example.com')
await waitFor(() => {
expect(mockInvite).toHaveBeenCalledWith(
expect.objectContaining({
emails: ['alice@example.com', 'bob@example.com', 'carol@example.com'],
})
)
})
})
it('lowercases emails before sending', async () => {
customRender(<InviteMemberButton />)
await submitForm('User@Example.COM')
await waitFor(() => {
expect(mockInvite).toHaveBeenCalledWith(
expect.objectContaining({ emails: ['user@example.com'] })
)
})
})
it('shows a validation error for an invalid email', async () => {
customRender(<InviteMemberButton />)
await openDialog()
fireEvent.change(screen.getByPlaceholderText(/name@example\.com/i), {
target: { value: 'not-an-email' },
})
fireEvent.click(screen.getByRole('button', { name: /send invitation/i }))
expect(await screen.findByText(/invalid email address: "not-an-email"/i)).toBeInTheDocument()
expect(mockInvite).not.toHaveBeenCalled()
})
it('shows an error toast and skips the mutation for an already-existing member', async () => {
customRender(<InviteMemberButton />)
await submitForm('existing@example.com')
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith(
'existing@example.com is already in this organization'
)
})
expect(mockInvite).not.toHaveBeenCalled()
})
it('still invites new emails in a batch that also contains an existing member', async () => {
customRender(<InviteMemberButton />)
await submitForm('new@example.com, existing@example.com')
await waitFor(() => {
expect(toast.error).toHaveBeenCalled()
expect(mockInvite).toHaveBeenCalledWith(
expect.objectContaining({ emails: ['new@example.com'] })
)
})
})
it('shows a success toast for a single email in succeeded', async () => {
mockInvite.mockResolvedValueOnce({ succeeded: ['new@example.com'], failed: [] })
customRender(<InviteMemberButton />)
await submitForm('new@example.com')
await waitFor(() => {
expect(toast.success).toHaveBeenCalledWith('Successfully sent invitation to new member')
})
})
it('shows a plural success toast when multiple emails succeeded', async () => {
mockInvite.mockResolvedValueOnce({
succeeded: ['alice@example.com', 'bob@example.com'],
failed: [],
})
customRender(<InviteMemberButton />)
await submitForm('alice@example.com, bob@example.com')
await waitFor(() => {
expect(toast.success).toHaveBeenCalledWith('Successfully sent invitations to 2 new members')
})
})
it('shows an error toast with the server error for each failed email', async () => {
mockInvite.mockResolvedValueOnce({
succeeded: [],
failed: [{ email: 'new@example.com', error: 'Domain not allowed' }],
})
customRender(<InviteMemberButton />)
await submitForm('new@example.com')
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith(
'Failed to invite new@example.com: Domain not allowed'
)
})
expect(toast.success).not.toHaveBeenCalled()
})
it('shows both success and error toasts for a partial batch result', async () => {
mockInvite.mockResolvedValueOnce({
succeeded: ['alice@example.com'],
failed: [{ email: 'bob@example.com', error: 'Domain not allowed' }],
})
customRender(<InviteMemberButton />)
await submitForm('alice@example.com, bob@example.com')
await waitFor(() => {
expect(toast.success).toHaveBeenCalledWith('Successfully sent invitation to new member')
expect(toast.error).toHaveBeenCalledWith(
'Failed to invite bob@example.com: Domain not allowed'
)
})
})
})