Files
supabase/apps/studio/tests/components/Organization/TeamSettings/InviteMemberButton.utils.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

239 lines
7.9 KiB
TypeScript

import { describe, expect, test } from 'vitest'
import {
buildProjectPayload,
buildSsoPayload,
categorizeInviteEmails,
emailSchema,
MAX_BATCH_INVITE_SIZE,
parseEmails,
} from '@/components/interfaces/Organization/TeamSettings/InviteMemberButton.utils'
import type { OrganizationMember } from '@/data/organizations/organization-members-query'
describe('parseEmails', () => {
test('parses a single email', () => {
expect(parseEmails('user@example.com')).toStrictEqual(['user@example.com'])
})
test('parses multiple comma-separated emails', () => {
expect(parseEmails('a@example.com,b@example.com,c@example.com')).toStrictEqual([
'a@example.com',
'b@example.com',
'c@example.com',
])
})
test('trims whitespace around each email', () => {
expect(parseEmails(' a@example.com , b@example.com ')).toStrictEqual([
'a@example.com',
'b@example.com',
])
})
test('filters out empty entries from trailing, leading, or double commas', () => {
expect(parseEmails(',a@example.com,,b@example.com,')).toStrictEqual([
'a@example.com',
'b@example.com',
])
})
test('removes duplicate email addresses', () => {
expect(parseEmails('a@example.com,a@example.com')).toStrictEqual(['a@example.com'])
})
test.each(['', ' ', ',,,,'])('returns an empty array for %j', (value) => {
expect(parseEmails(value)).toStrictEqual([])
})
test('parses space-separated emails', () => {
expect(parseEmails('a@example.com b@example.com')).toStrictEqual([
'a@example.com',
'b@example.com',
])
})
test('parses line breaks and mixed comma or space separators', () => {
expect(parseEmails('a@example.com\nb@example.com, c@example.com')).toStrictEqual([
'a@example.com',
'b@example.com',
'c@example.com',
])
})
})
function makeMember(overrides: Partial<OrganizationMember> = {}): OrganizationMember {
return {
gotrue_id: 'gotrue-1',
primary_email: 'member@example.com',
role_ids: [1],
username: 'member',
...overrides,
} as OrganizationMember
}
describe('categorizeInviteEmails', () => {
test('places a new email in toInvite when no members exist', () => {
expect(categorizeInviteEmails(['new@example.com'], [])).toStrictEqual({
alreadyInvited: [],
alreadyMembers: [],
toInvite: ['new@example.com'],
})
})
test('places an email in alreadyMembers when that member exists without an invited_id', () => {
const members = [makeMember({ primary_email: 'existing@example.com' })]
expect(categorizeInviteEmails(['existing@example.com'], members)).toStrictEqual({
alreadyInvited: [],
alreadyMembers: ['existing@example.com'],
toInvite: [],
})
})
test('places an email in alreadyInvited when that member has an invited_id', () => {
const members = [makeMember({ primary_email: 'invited@example.com', invited_id: 42 })]
expect(categorizeInviteEmails(['invited@example.com'], members)).toStrictEqual({
alreadyInvited: ['invited@example.com'],
alreadyMembers: [],
toInvite: [],
})
})
test('correctly categorizes a mixed batch', () => {
const members = [
makeMember({ primary_email: 'member@example.com' }),
makeMember({ primary_email: 'invited@example.com', invited_id: 7 }),
]
expect(
categorizeInviteEmails(
['new@example.com', 'member@example.com', 'invited@example.com'],
members
)
).toStrictEqual({
alreadyInvited: ['invited@example.com'],
alreadyMembers: ['member@example.com'],
toInvite: ['new@example.com'],
})
})
test('returns all-empty for an empty email list', () => {
expect(categorizeInviteEmails([], [makeMember()])).toStrictEqual({
alreadyInvited: [],
alreadyMembers: [],
toInvite: [],
})
})
test('uses strict equality — does not match different casing', () => {
// The component lowercases emails before calling this function,
// so 'member@example.com' must NOT match 'Member@Example.com'
const members = [makeMember({ primary_email: 'Member@Example.com' })]
const result = categorizeInviteEmails(['member@example.com'], members)
expect(result.toInvite).toStrictEqual(['member@example.com'])
expect(result.alreadyMembers).toStrictEqual([])
})
})
describe('buildProjectPayload', () => {
test('returns empty object when applyToOrg is true', () => {
expect(buildProjectPayload(true, [])).toStrictEqual({})
})
test('throws an error when applyToOrg is false but no projects are selected', () => {
expect(() => buildProjectPayload(false, [])).toThrowError(
'At least one project is required when applyToOrg is false'
)
})
test('returns all selected projects when applyToOrg is false and multiple are selected', () => {
expect(buildProjectPayload(false, ['ref_abc', 'ref_def', 'ref_ghi'])).toStrictEqual({
projects: ['ref_abc', 'ref_def', 'ref_ghi'],
})
})
})
describe('buildSsoPayload', () => {
test('returns empty object for "auto"', () => {
expect(buildSsoPayload('auto')).toStrictEqual({})
})
test('returns { requireSso: true } for "sso"', () => {
expect(buildSsoPayload('sso')).toStrictEqual({ requireSso: true })
})
test('returns { requireSso: false } for "non-sso"', () => {
expect(buildSsoPayload('non-sso')).toStrictEqual({ requireSso: false })
})
})
function makeEmailList(count: number): string {
return Array.from({ length: count }, (_, i) => `user${i + 1}@example.com`).join(', ')
}
function makeEmailListSpaceSeparated(count: number): string {
return Array.from({ length: count }, (_, i) => `user${i + 1}@example.com`).join(' ')
}
describe('emailSchema', () => {
test('accepts a single valid email', () => {
expect(emailSchema.safeParse('user@example.com').success).toBe(true)
})
test('accepts exactly 50 emails', () => {
expect(emailSchema.safeParse(makeEmailList(MAX_BATCH_INVITE_SIZE)).success).toBe(true)
})
test('rejects 51 emails — singular "address" when exactly 1 needs removing', () => {
const result = emailSchema.safeParse(makeEmailList(51))
expect(result.success).toBe(false)
if (!result.success) {
expect(result.error.issues[0].message).toBe(
'You can invite up to 50 members at a time. Remove 1 email address to continue.'
)
}
})
test('rejects 51 space-separated emails (same as comma-separated batch limit)', () => {
const result = emailSchema.safeParse(makeEmailListSpaceSeparated(51))
expect(result.success).toBe(false)
if (!result.success) {
expect(result.error.issues[0].message).toBe(
'You can invite up to 50 members at a time. Remove 1 email address to continue.'
)
}
})
test('rejects 99 emails — plural "addresses" when more than 1 needs removing', () => {
const result = emailSchema.safeParse(makeEmailList(99))
expect(result.success).toBe(false)
if (!result.success) {
expect(result.error.issues[0].message).toBe(
'You can invite up to 50 members at a time. Remove 49 email addresses to continue.'
)
}
})
test('rejects an empty string', () => {
const result = emailSchema.safeParse('')
expect(result.success).toBe(false)
})
test('rejects an invalid email address and names it', () => {
const result = emailSchema.safeParse('notanemail')
expect(result.success).toBe(false)
if (!result.success) {
expect(result.error.issues[0].message).toBe('Invalid email address: "notanemail"')
}
})
test('truncates a very long invalid token in the error message', () => {
const longToken = `${'x'.repeat(130)}@`
const result = emailSchema.safeParse(longToken)
expect(result.success).toBe(false)
if (!result.success) {
expect(result.error.issues[0].message.startsWith('Invalid email address: "')).toBe(true)
expect(result.error.issues[0].message.endsWith('…"')).toBe(true)
expect(result.error.issues[0].message.length).toBeLessThan(longToken.length + 50)
}
})
})