mirror of
https://github.com/AmruthPillai/Reactive-Resume.git
synced 2026-07-14 06:47:00 +10:00
test: add ~500 tests across web, utils, api, import, ai, db, email, auth (#3038)
* test(web): add tests for zustand stores and pure helpers
Cover stores and pure helpers across the builder/dashboard/command-palette
surfaces that previously had 0% coverage:
- command-palette store (open/close, page stack, search clearing, goBack)
- builder assistant-store
- builder sidebar store + parseBuilderLayoutCookie / mapPanelLayoutToBuilderLayout
- builder section store (collapse, toggle, toggleAll)
- builder preview page-layout toggle
- dashboard resume-thumbnail render-size math + cache key
- MCP tool name + annotations invariants
* test(web): cover MCP helpers and template metadata
Add tests for previously 0%-coverage MCP and dialog helpers:
- buildMcpServerCard: server-info, tool catalog vs MCP_TOOL_NAME, prompts,
resource templates, configuration schema, auth schemes
- registerPrompts (build/improve/review): registration, args schema, resource
context with interpolated resume id, read-only / no-fabrication directives
- registerResources (resume://{id}, resume://_meta/schema): handler reads via
oRPC client, error on missing id, schema returns valid JSON
- templates metadata: ids match display names, valid sidebar positions,
unique image URLs, every entry has tags + description
* test(web): cover sidebar section helpers and layout screens
Add tests for previously near-0%-coverage modules:
- libs/resume/section: getSectionTitle / getSectionIcon return distinct,
exhaustive results for every sidebar section + cover-letter; icon props
forwarding; left/right sidebar collections do not overlap.
- layout/loading-screen: spinner + text render.
- layout/error-screen: error message surfaces, Refresh button triggers reset.
- layout/breakpoint-indicator: default + each corner positioning, all
breakpoint labels rendered, print-hidden class applied.
* test(web): cover preview canvas math and font-weight defaults
Add tests for pure helpers that previously had no direct coverage:
- typography/getNextWeights: prefers 400 + 600 when both are available,
returns null for unknown families, never produces duplicates, bounded
to two weights from the 100..900 set.
- preview.shared/normalizeResumePreviewProps: documented defaults +
pass-through.
- preview.shared/getScaledPreviewPageSize: scaling identity at 1, and
fractional scaling.
- preview.shared/getPreviewCanvasScale: respects 4x desired scale for
small pages, honors high devicePixelRatio, clamps to the 16M-pixel
canvas budget for large pages.
* test(utils): cover DOCX section renderers and html-to-paragraphs
@reactive-resume/utils/resume/docx was previously at ~2.84% statement
coverage despite being load-bearing for the resume DOCX export.
- section-renderers: empty-string / hidden-section / hidden-item branches
for renderSummary, renderBuiltInSection, and renderCustomSection;
cover-letter and summary custom-section dispatch; unknown-type fallback;
setRenderConfig idempotency.
- html-to-docx: whitespace-only short-circuit, multiple top-level blocks,
h1..h6 paragraph mapping, inline style and link rendering, custom
font/size/color/linkColor config, ignored script/comment nodes.
* test: cover DOCX builder smoke paths and reactive-resume JSON importer
- utils/resume/docx/builder: buildDocument runs end-to-end against the
default and sample resume data, both page formats, full-width and
sidebar layouts, and gracefully degrades with unparseable color or
empty font family inputs.
- import/reactive-resume-json: ReactiveResumeJSONImporter validates
malformed JSON, recovers missing built-in sections by appending them
to page 1 without reordering, and preserves layouts that already
contain every built-in section.
* test(import): cover JSONResumeImporter parse/convert
JSONResumeImporter (450 lines) was previously at 0% coverage. Add tests
for the public surface:
- Invalid JSON / invalid-shape errors are surfaced.
- basics, summary, picture, education, projects, skills, profiles all
map to the corresponding ResumeData sections.
- Empty work/education entries (missing key field) are filtered out.
- Highlights become HTML list items in the description field.
- Skill level parsing flows through utils/level.parseLevel.
- formatLocation joins city, region, countryCode with commas.
* test(web): cover query client serializer and home-page animations
- libs/query/client: getQueryClient returns a fresh QueryClient,
queryKeyHashFn produces stable JSON envelopes for matching keys
(and distinct strings for different keys), dehydrate/hydrate
round-trip Date values via the oRPC serializer.
- components/animation/spotlight: overlay container is
pointer-events-none, both beam groups render, custom
width/height/translateY/gradient props flow into inline styles.
- components/animation/comet-card: children mount inside the
perspective wrapper, custom className is merged with the 3D
baseline classes, glare overlay renders, mouse move/leave
handlers do not throw.
* test(web): cover Copyright footer
Verify the footer's MIT license link, Amruth Pillai attribution,
external-tab targets, embedded app version (via __APP_VERSION__ stub),
and custom className merging — previously at 0% coverage.
* test(api): cover flags, auth providers, and resume-access cookies
Unlock @reactive-resume/api by mocking @reactive-resume/env/server and
@tanstack/react-start/server. Previously the only services tested were
the standalone AI test and resume-access-policy.
- services/flags: flagsService.getFlags reads disableSignups/disableEmailAuth
from env (no stale cache).
- services/auth: providers.list always exposes credential + passkey, and
only adds Google/GitHub/LinkedIn/custom when both id and secret are set;
custom provider uses OAUTH_PROVIDER_NAME with a 'Custom OAuth' fallback.
- helpers/resume-access: hasResumeAccess validates against signed cookies
with constant-time comparison; grantResumeAccess writes a 10-minute
httpOnly cookie with the secure flag matching APP_URL's https-ness.
* test: cover statistics service and email transport via env mocks
- api/services/statistics: github star count succeeds, retries on
non-OK, falls back to last-known on fetch error / non-positive /
non-numeric responses; user and resume counts roll up DB count.
- email/src/transport: returns silently with no text/html, logs when
SMTP is not configured, dispatches via nodemailer with the env
config when fully wired, renders react elements to html + text
bodies, swallows transport errors instead of crashing.
* test(api): cover resume-events publish + subscribe
- publishResumeUpdated issues pg_notify with channel and serialized
event payload.
- subscribeResumeUpdated yields events whose resumeId+userId match
the subscription, filters out other resumes/users, ignores
malformed JSON and notifications on other channels, calls
LISTEN/UNLISTEN and releases the client, and terminates
immediately if the abort signal fires before iteration starts.
* test(api): cover oRPC auth resolution
resolveUserFromRequestHeaders is the single point where every oRPC
procedure picks up the authenticated user. Test the priority chain:
- x-api-key wins when present and valid
- on invalid api key, falls back to session via auth.api.getSession
- Bearer JWT in Authorization header is verified via verifyOAuthToken
- invalid Bearer falls back to session
- Authorization scheme other than Bearer is ignored entirely
- thrown errors from token verification are logged and swallowed
(caller still tries session)
- returns null when no auth method succeeds
* test(api): cover storage helpers
inferContentType, isImageFile, processImageForUpload were 0%
coverage despite being on the picture upload path.
- inferContentType maps known image and pdf extensions, is
case-insensitive, ignores path depth, and falls back to
application/octet-stream for unknown.
- isImageFile allows only the upload allowlist (gif/png/jpeg/webp)
and rejects image/svg+xml, application/pdf, and empty strings.
- processImageForUpload short-circuits to the original bytes when
FLAG_DISABLE_IMAGE_PROCESSING is true, otherwise pipes through
sharp and returns image/jpeg.
* test(import): broaden v4 importer section-mapping coverage
The existing v4 importer test focused on a single bug (description-only
custom items) and the skill/language level scaling. This new test
exercises the bulk of the v4 → v5 transformation path:
- basics, picture (with border), summary, customFields
- every section's filter-by-required-field invariant (awards needs
title, certifications needs name, education needs institution,
experience needs company, volunteer needs organization, etc.)
- experience / education / awards / certifications / references field
renames between schemas
- language and skill level scaling (v4 0..10 → v5 0..5)
Brings reactive-resume-v4-json from ~66% statement coverage to a
materially higher figure (the bulk of the 410-line transformer body).
* test: cover buildDocx entry and AI configuration store
- utils/resume/docx/index: buildDocx returns a non-empty Blob for both
default and populated resumes (previously 0% coverage despite being
the public DOCX entry point).
- ai/store: useAIStore preserves verification status across no-op
updates, but resets testStatus + enabled whenever provider, model,
apiKey, or baseURL changes; canEnable is gated to testStatus=success;
setEnabled(true) is refused unless verified; reset clears every
field. Brings @reactive-resume/ai from ~72% to materially higher
coverage.
* test(db): cover resume schema definitions
packages/db was previously at 0% coverage. Smoke-test the public
resume / resume_statistics / resume_analysis tables:
- getTableName matches the SQL identifier used by migrations
- expected columns are present on each table
- defaultResumeData wiring on the data column resolves to a valid
shape
These are structural assertions that catch accidental renames /
removals without needing a live database connection.
* test(db): cover auth schema tables and relations export
- src/schema/auth: table-driven test for each of the 12 auth tables
asserting SQL name and presence of the key columns (user/session/
account/verification/two_factor/passkey/apikey/jwks/oauth_*).
- src/relations: smoke test confirming the relations export is defined.
Brings @reactive-resume/db from 0% to materially higher coverage.
* test(auth): cover getSession isomorphic helper
@reactive-resume/auth was previously at 0% coverage. functions.ts
is the server entry point that other packages call. Mock the auth
config + tanstack/react-start to verify:
- getSession forwards getRequestHeaders() to auth.api.getSession
- returns null when better-auth returns null
* test(web): cover BuilderSidebarEdge
Small presentational component on the builder layout — assert children
mount, left/right positioning class branches, and the sm:flex
mobile-hide behavior.
* test(web): cover section-title-locale resolver cache and hook
The section-title-locale module wraps createSectionTitleResolver with
a per-locale async cache and a React hook for consumers in the
builder. Cover:
- createSectionTitleResolverForLocale returns a usable resolver
- repeated calls for the same locale share a cached promise
- unknown locales fall back through resolveLocale
- useSectionTitleResolver returns null while loading and when no
locale is passed
- the hook resolves to a function once the async loader settles
* test(web): cover BaseCommandGroup page-stack gating
BaseCommandGroup conditionally renders based on the top of the
command-palette page stack. Tests cover:
- root group renders when no sub-page is active
- root group hides when a sub-page is on top
- sub-page group renders only when its page matches
- mismatched sub-page leaves the group hidden
* test(web): cover ThemeProvider context
- useTheme outside ThemeProvider throws the documented error
- useTheme inside ThemeProvider returns the theme + setTheme +
toggleTheme helpers
* test(web): cover ConfirmDialogProvider + useConfirm hook
- useConfirm outside provider throws the documented error
- confirm returns a pending promise
- promise resolves false when the Cancel button is clicked
- promise resolves true when the Confirm button is clicked
- works with custom confirmText label
apps/web has its own copy of this hook distinct from
packages/ui (mirrors the existing UI-package tests).
* test(web): cover PromptDialogProvider + usePrompt hook
- usePrompt outside provider throws the documented error
- returns a function when wrapped
- Cancel click resolves the promise to null
- Confirm click resolves to the current input value
- defaultValue option seeds the initial input value
* test(web): cover DashboardHeader
Small presentational header used across dashboard routes — title h1,
icon rendering, className merge, mobile sidebar trigger present and
hidden on md+.
* test(web): cover Create/Import resume cards
Both cards on the resumes dashboard wire a click handler to open
the appropriate dialog via the dialog store:
- CreateResumeCard opens resume.create
- ImportResumeCard opens resume.import
Also asserts the i18n copy strings (icons aside, the cards are
otherwise structural).
* test(web): cover command-palette language sub-page
LanguageCommandPage is a BaseCommandGroup gated on page='language'.
Tests assert:
- it is hidden when 'language' is not the top of the page stack
- when active, it renders a CommandItem per localeMap entry
- documented locale codes (en-US, de-DE, ja-JP) appear
* test(web): cover command-palette theme + preferences sub-pages
- ThemeCommandPage: hidden when 'theme' is not on top, renders Light
and Dark options when active
- PreferencesCommandGroup: root group renders both Change theme to...
and Change language to... items; clicking each pushes the
corresponding page onto the command-palette stack
* test(ai): cover executePatchResume tool
- patchResumeInputSchema rejects empty operations and unknown op
values; accepts valid replace/add/remove
- executePatchResume returns the applied operations on success
- executePatchResume throws when an operation targets an invalid path
(passes through the underlying applyResumePatches validation)
- multi-op patches against top-level fields succeed end-to-end
* test(ai): cover sanitize edge branches
Hit the previously-uncovered branches in sanitize.ts:
- numeric 1 coerces to true
- '1' / '0' string shorthand coerces to true/false
- missing item.hidden gets salvaged to false
- empty input causes a non-Zod throw (caught + rethrown with generic message)
* test(ai): cover patch-proposal preview + normalize edge cases
- remove operations surface before-value with after=undefined
- buildResumePatchProposalPreview labels metadata/page paths sanely
- normalizeResumePatchProposals stamps every proposal with baseUpdatedAt
- normalizeResumePatchProposals preserves input order
* test(web): cover getLocaleOptions helper
Locale combobox surface — verify the option list mirrors localeMap
shape, uses locale codes as values, populates label + keywords with
the translated display name, and produces unique values.
* test(web): cover LevelTypeCombobox option mapping
LevelTypeCombobox maps levelDesignSchema.shape.type.options through
the internal getLevelTypeName labeler. Assert all 7 level types are
exposed and that each produces a non-empty label.
* test(web): cover ThemeToggleButton fallback paths
- aria-label flips between 'Switch to light theme' and 'Switch to
dark theme' based on current theme
- clicking when document.startViewTransition is unavailable
short-circuits to toggleTheme directly
- prefers-reduced-motion forces the direct toggle path even when
the view-transition API is available
* test(web): cover NotFoundScreen
Mock the TanStack Router Link so the screen renders standalone, then
assert: documented error heading, routeId is surfaced verbatim, and
the Go Back link points to '..' (parent route).
* test(web): cover InformationSectionBuilder
Stub SectionBase so the donation/info section renders standalone.
Assert: donation prompt copy, OpenCollective CTA link, all 5
external resource links present, and external links target _blank
with rel=noopener.
* test(web): cover NotesSectionBuilder
Mock SectionBase, RichInput, and the resume-draft hooks so the
notes section renders in isolation. Assert: privacy hint copy
renders, RichInput is seeded with metadata.notes, and onChange
proxies through updateResumeData with a draft recipe that mutates
metadata.notes.
* test(web): cover TemplateSectionBuilder
Stub SectionBase and useCurrentResume so the right-sidebar template
section renders standalone. Asserts: current template name in the
heading, template tags rendered as badges, preview image points to
the catalog asset, and clicking the preview opens the
resume.template.gallery dialog.
* test(web): cover ColorPicker preset selection and trigger override
Mock the heavy @uiw/react-color-colorful dependency. Test:
- the trigger swatch reflects the controlled value
- clicking a preset color invokes onChange with an rgba() string
- a custom trigger replaces the default swatch when provided
* test(web): cover ExportSectionBuilder
Mock the heavy export pipelines (buildDocx, createResumePdfBlob,
downloadWithAnchor) and the resume-draft hook to test:
- JSON button packages resume.data as application/json and triggers
download with the {name}.json filename
- DOCX button awaits buildDocx and downloads .docx
- PDF button awaits createResumePdfBlob and downloads .pdf
* test(web): cover ProfilesSectionBuilder
Stub the resume-draft hooks, SectionBase, SectionItem, and
SectionAddItemButton so the profiles section renders standalone:
- one SectionItem per profile with network as title and username as
subtitle
- 'Add a new profile' affordance present
- when items.length > 0, the wrapper uses a solid border (not dashed)
* test(web): cover SkillsSectionBuilder
Mirror the profiles test for the skills section — verifies one
SectionItem per skill (name → title, proficiency → subtitle) and
the Add a new skill affordance.
* test(web): bulk-cover 7 left-sidebar section builders
Single test file covers awards, certifications, interests, languages,
publications, references, and volunteer builders. For each:
- one SectionItem rendered with the documented field → title/subtitle
mapping
- awards: title → awarder
- certifications: title → 'issuer • date'
- interests: name → (no subtitle)
- languages: language → fluency
- publications: title → publisher
- references: name → (no subtitle)
- volunteer: organization → location
- the 'Add a new {kind}' affordance with the matching copy
Mocks SectionBase, SectionItem, SectionAddItemButton, and the
resume-draft hooks so each builder renders standalone.
* test(web): cover ProjectsSectionBuilder buildSubtitle
The projects section is the only left-sidebar builder with a
composite subtitle. Tests three branches of its inline
buildSubtitle helper:
- period + website.label → joined with ' • '
- period only → just the period
- empty period + whitespace-only website.label → returns undefined
* test(web): cover Education + Experience section builders
- Education: school → title, degree → subtitle, add-new affordance
- Experience: position → subtitle when set; falls back to '1 role' /
'N roles' (lingui plural) when position empty and roles[] present;
add-new affordance
* test(web): cover CountUp animated number renderer
- default aria attributes (aria-live=polite, aria-atomic=true)
- initial textContent seeds to 'from' (up) or 'to' (down) value
- separator option formats with grouping
- decimal places are preserved when from/to are fractional
- aria-hidden=true strips aria-live + aria-atomic
- custom className is applied to the rendered span
* test(web): cover TextMaskEffect SVG renderer
- supplied text renders in every visible <text> layer
- aria-hidden + aria-label forwarded onto the root svg
- mouse enter/move/leave handlers don't throw
- custom className merges into the svg's class attribute
* test(web): cover URLInput prefix handling
- displayed input strips the https:// prefix so users only edit the
meaningful portion
- editing re-adds the prefix on the way back through onChange
- pre-prefixed input is preserved
- cleared input emits an empty url (no prefix forced)
- hideLabelButton=true removes the popover trigger; default keeps it
* test(web): cover GithubStarsButton
Mocks useQuery + the CountUp animation so the button renders
standalone. Asserts:
- anchor points at the project repo with rel=noopener + target=_blank
- aria-label is the no-count copy when star count is undefined
- CountUp renders only once the count loads
- aria-label includes the localized count once data arrives
* test(web): cover ui/Combobox trigger label rendering
The shared Combobox wraps base-ui's combobox primitives. Smoke-test
the trigger label resolution:
- placeholder shows when nothing is selected
- selected option's label renders in the trigger
- multi-select default values render all labels
- empty options array renders the placeholder without crashing
* test(web): cover IconPicker trigger rendering
Stub react-window's Grid so happy-dom can render the picker without
layout-measurement deps. Verify:
- trigger renders an <i class='ph-{value}'> for the current value
- changing value updates the trigger icon class
- the picker emits a trigger button
* test(web): cover ChipInput add/dedupe/description behaviors
- existing chips render as Badges
- Enter adds the typed value to the chip list
- comma also commits the typed value
- duplicate input is dropped (onChange not called with a longer list)
- empty / whitespace-only input is dropped
- hideDescription removes the keyboard hint <kbd>; default keeps it
* test(web): cover StatisticsSectionBuilder
Mock useQuery + useParams + section-base so the right-sidebar
statistics section renders standalone:
- returns null content while the query is loading
- shows the private-resume hint when isPublic=false
- shows views/downloads counters and labels when isPublic=true
- includes 'Last viewed' timestamp copy when lastViewedAt is set
* test(web): cover TemplateGalleryDialog selection flow
- title + intro copy render
- one tile per template (>= 14)
- currently-selected template tile carries the ring-highlight
- clicking a different tile triggers updateResumeData with a recipe
that sets metadata.template to the chosen template id
* test(web): cover Prefooter home-page section
- community tagline heading renders
- community-thanks paragraph renders
- the decorative TextMaskEffect renders an svg
* test(web): cover home-page Footer
- Resources and Community headings render
- documented resource links (Documentation, Sponsorships, Source
Code, Changelog) all appear in the rendered output
- documented community links (Report an issue, Translations,
Subreddit, Discord) all appear
- social anchors point at GitHub, LinkedIn, and X (Twitter)
- Copyright sub-component surfaces the app version via __APP_VERSION__
* test(web): cover home-page Header navigation
Mock TanStack Router Link + child components so the header renders
standalone. Verify:
- homepage anchor (/ link) carries the documented aria-label
- dashboard anchor points to /dashboard
- ThemeToggleButton and GithubStarsButton both mount
- the <nav> landmark is labeled 'Main navigation'
* chore: fix linter warnings
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CometCard } from "./comet-card";
|
||||
|
||||
describe("CometCard", () => {
|
||||
it("renders its children inside the perspective wrapper", () => {
|
||||
const { getByText } = render(
|
||||
<CometCard>
|
||||
<span>card body</span>
|
||||
</CometCard>,
|
||||
);
|
||||
expect(getByText("card body")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("merges custom className into the wrapper", () => {
|
||||
const { container } = render(
|
||||
<CometCard className="extra-class">
|
||||
<span>x</span>
|
||||
</CometCard>,
|
||||
);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("extra-class");
|
||||
expect(wrapper.className).toContain("perspective-distant");
|
||||
expect(wrapper.className).toContain("transform-3d");
|
||||
});
|
||||
|
||||
it("renders a glare overlay positioned absolutely with mix-blend-overlay", () => {
|
||||
const { container } = render(
|
||||
<CometCard>
|
||||
<span>x</span>
|
||||
</CometCard>,
|
||||
);
|
||||
const glare = container.querySelector("[class*='mix-blend-overlay']") as HTMLElement | null;
|
||||
expect(glare).not.toBeNull();
|
||||
expect(glare?.className).toContain("pointer-events-none");
|
||||
});
|
||||
|
||||
it("does not throw when mouse enters / moves over / leaves the card", () => {
|
||||
const { container } = render(
|
||||
<CometCard>
|
||||
<span>x</span>
|
||||
</CometCard>,
|
||||
);
|
||||
|
||||
const tiltable = container.querySelector("[class*='will-change-transform']") as HTMLElement;
|
||||
expect(tiltable).toBeTruthy();
|
||||
|
||||
expect(() => {
|
||||
fireEvent.mouseMove(tiltable, { clientX: 100, clientY: 50 });
|
||||
fireEvent.mouseMove(tiltable, { clientX: 0, clientY: 0 });
|
||||
fireEvent.mouseLeave(tiltable);
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CountUp } from "./count-up";
|
||||
|
||||
describe("CountUp", () => {
|
||||
it("renders an aria-live=polite span by default (announced to screen readers)", () => {
|
||||
const { container } = render(<CountUp to={1000} />);
|
||||
const span = container.querySelector("span") as HTMLSpanElement;
|
||||
expect(span.getAttribute("aria-live")).toBe("polite");
|
||||
expect(span.getAttribute("aria-atomic")).toBe("true");
|
||||
});
|
||||
|
||||
it("seeds textContent to the 'from' value when counting up", () => {
|
||||
const { container } = render(<CountUp from={0} to={100} />);
|
||||
const span = container.querySelector("span") as HTMLSpanElement;
|
||||
expect(span.textContent).toBe("0");
|
||||
});
|
||||
|
||||
it("seeds textContent to the 'to' value when direction is down", () => {
|
||||
const { container } = render(<CountUp from={0} to={100} direction="down" />);
|
||||
const span = container.querySelector("span") as HTMLSpanElement;
|
||||
expect(span.textContent).toBe("100");
|
||||
});
|
||||
|
||||
it("formats with the separator when one is supplied", () => {
|
||||
const { container } = render(<CountUp from={1234} to={2345} separator="," />);
|
||||
const span = container.querySelector("span") as HTMLSpanElement;
|
||||
expect(span.textContent).toBe("1,234");
|
||||
});
|
||||
|
||||
it("preserves decimal places when from / to are fractional", () => {
|
||||
const { container } = render(<CountUp from={1.25} to={3.75} />);
|
||||
const span = container.querySelector("span") as HTMLSpanElement;
|
||||
expect(span.textContent).toBe("1.25");
|
||||
});
|
||||
|
||||
it("strips aria-live and aria-atomic when aria-hidden is set", () => {
|
||||
const { container } = render(<CountUp to={100} aria-hidden="true" />);
|
||||
const span = container.querySelector("span") as HTMLSpanElement;
|
||||
expect(span.getAttribute("aria-hidden")).toBe("true");
|
||||
expect(span.getAttribute("aria-live")).toBeNull();
|
||||
expect(span.getAttribute("aria-atomic")).toBeNull();
|
||||
});
|
||||
|
||||
it("accepts a custom className", () => {
|
||||
const { container } = render(<CountUp to={100} className="custom-class" />);
|
||||
const span = container.querySelector("span") as HTMLSpanElement;
|
||||
expect(span.className).toContain("custom-class");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Spotlight } from "./spotlight";
|
||||
|
||||
describe("Spotlight", () => {
|
||||
it("renders a non-pointer-events overlay container", () => {
|
||||
const { container } = render(<Spotlight />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("pointer-events-none");
|
||||
expect(wrapper.className).toContain("absolute");
|
||||
});
|
||||
|
||||
it("renders both left and right beam groups by default", () => {
|
||||
const { container } = render(<Spotlight />);
|
||||
// Outer wrapper > two animated beam containers
|
||||
const beamGroups = container.firstChild?.childNodes;
|
||||
expect(beamGroups?.length).toBe(2);
|
||||
});
|
||||
|
||||
it("applies the provided width / height / smallWidth to inline styles", () => {
|
||||
const { container } = render(<Spotlight width={500} height={800} smallWidth={120} translateY={-100} />);
|
||||
|
||||
const inlineStyles = Array.from(container.querySelectorAll<HTMLDivElement>("[style]")).map(
|
||||
(el) => el.getAttribute("style") ?? "",
|
||||
);
|
||||
const allStyles = inlineStyles.join("|");
|
||||
|
||||
expect(allStyles).toContain("width: 500px");
|
||||
expect(allStyles).toContain("height: 800px");
|
||||
expect(allStyles).toContain("width: 120px");
|
||||
expect(allStyles).toContain("translateY(-100px)");
|
||||
});
|
||||
|
||||
it("uses the supplied gradient strings as background values", () => {
|
||||
const customFirst = "radial-gradient(red, blue)";
|
||||
const { container } = render(<Spotlight gradientFirst={customFirst} />);
|
||||
|
||||
const matched = Array.from(container.querySelectorAll<HTMLDivElement>("[style]")).filter(
|
||||
(el) => el.style.background.includes("red") && el.style.background.includes("blue"),
|
||||
);
|
||||
expect(matched.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { TextMaskEffect } from "./text-mask";
|
||||
|
||||
const renderMask = (props: React.ComponentProps<typeof TextMaskEffect>) => render(<TextMaskEffect {...props} />);
|
||||
|
||||
describe("TextMaskEffect", () => {
|
||||
it("renders the supplied text in all visible text layers", () => {
|
||||
const { container } = renderMask({ text: "Hello World" });
|
||||
const texts = container.querySelectorAll("text");
|
||||
expect(texts.length).toBeGreaterThanOrEqual(2);
|
||||
for (const el of texts) {
|
||||
expect(el.textContent).toBe("Hello World");
|
||||
}
|
||||
});
|
||||
|
||||
it("forwards aria-hidden onto the root svg", () => {
|
||||
const { container } = renderMask({ text: "X", "aria-hidden": "true" });
|
||||
const svg = container.querySelector("svg") as SVGSVGElement;
|
||||
expect(svg.getAttribute("aria-hidden")).toBe("true");
|
||||
});
|
||||
|
||||
it("renders an aria-label on the root svg", () => {
|
||||
const { container } = renderMask({ text: "X" });
|
||||
const svg = container.querySelector("svg") as SVGSVGElement;
|
||||
expect(svg.getAttribute("aria-label")).toBe("Text mask effect");
|
||||
});
|
||||
|
||||
it("does not throw on mouse-enter / mouse-move / mouse-leave interactions", () => {
|
||||
const { container } = renderMask({ text: "X" });
|
||||
const svg = container.querySelector("svg") as SVGSVGElement;
|
||||
|
||||
expect(() => {
|
||||
fireEvent.mouseEnter(svg);
|
||||
fireEvent.mouseMove(svg, { clientX: 50, clientY: 25 });
|
||||
fireEvent.mouseLeave(svg);
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
it("merges custom className into the svg", () => {
|
||||
const { container } = renderMask({ text: "X", className: "custom-class" });
|
||||
const svg = container.querySelector("svg") as SVGSVGElement;
|
||||
expect(svg.getAttribute("class") ?? "").toContain("custom-class");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { Command } from "@reactive-resume/ui/components/command";
|
||||
import { useCommandPaletteStore } from "../store";
|
||||
import { BaseCommandGroup } from "./base";
|
||||
|
||||
const renderInCommand = (ui: React.ReactNode) => render(<Command>{ui}</Command>);
|
||||
|
||||
const resetStore = () => {
|
||||
useCommandPaletteStore.setState({ open: false, search: "", pages: [] });
|
||||
};
|
||||
|
||||
afterEach(resetStore);
|
||||
|
||||
describe("BaseCommandGroup", () => {
|
||||
it("renders children at the root (no page prop) when the page stack is empty", () => {
|
||||
renderInCommand(<BaseCommandGroup heading="Root">child-text</BaseCommandGroup>);
|
||||
expect(screen.getByText("child-text")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does NOT render when the page stack tops a different page than its `page` prop", () => {
|
||||
useCommandPaletteStore.setState({ pages: ["other"] });
|
||||
const { container } = renderInCommand(
|
||||
<BaseCommandGroup page="settings" heading="Settings">
|
||||
<span>x</span>
|
||||
</BaseCommandGroup>,
|
||||
);
|
||||
// Nothing rendered besides the Command shell itself.
|
||||
expect(container.textContent).toBe("");
|
||||
});
|
||||
|
||||
it("renders when the top of the page stack matches its `page` prop", () => {
|
||||
useCommandPaletteStore.setState({ pages: ["settings"] });
|
||||
renderInCommand(
|
||||
<BaseCommandGroup page="settings" heading="Settings">
|
||||
settings-children
|
||||
</BaseCommandGroup>,
|
||||
);
|
||||
expect(screen.getByText("settings-children")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does NOT render the root group when there is a sub-page on top", () => {
|
||||
useCommandPaletteStore.setState({ pages: ["settings"] });
|
||||
const { container } = renderInCommand(
|
||||
<BaseCommandGroup heading="Root">
|
||||
<span>root-text</span>
|
||||
</BaseCommandGroup>,
|
||||
);
|
||||
expect(container.textContent).toBe("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { Command } from "@reactive-resume/ui/components/command";
|
||||
import { useCommandPaletteStore } from "../../store";
|
||||
|
||||
vi.mock("@/components/theme/provider", () => ({
|
||||
useTheme: () => ({ setTheme: vi.fn(), theme: "light", toggleTheme: vi.fn() }),
|
||||
}));
|
||||
|
||||
const { PreferencesCommandGroup } = await import("./index");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useCommandPaletteStore.setState({ open: false, search: "", pages: [] });
|
||||
});
|
||||
|
||||
const renderGroup = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Command>
|
||||
<PreferencesCommandGroup />
|
||||
</Command>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("PreferencesCommandGroup", () => {
|
||||
it("renders 'Change theme to...' and 'Change language to...' at the root", () => {
|
||||
renderGroup();
|
||||
expect(screen.getByText("Change theme to...")).toBeInTheDocument();
|
||||
expect(screen.getByText("Change language to...")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("pushes 'theme' onto the page stack when the theme item is selected", () => {
|
||||
renderGroup();
|
||||
const item = screen.getByText("Change theme to...");
|
||||
fireEvent.click(item);
|
||||
expect(useCommandPaletteStore.getState().pages).toContain("theme");
|
||||
});
|
||||
|
||||
it("pushes 'language' onto the page stack when the language item is selected", () => {
|
||||
renderGroup();
|
||||
fireEvent.click(screen.getByText("Change language to..."));
|
||||
expect(useCommandPaletteStore.getState().pages).toContain("language");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { Command } from "@reactive-resume/ui/components/command";
|
||||
import { localeMap } from "@/libs/locale";
|
||||
import { useCommandPaletteStore } from "../../store";
|
||||
import { LanguageCommandPage } from "./language";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useCommandPaletteStore.setState({ open: false, search: "", pages: [] });
|
||||
});
|
||||
|
||||
const renderPage = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Command>
|
||||
<LanguageCommandPage />
|
||||
</Command>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("LanguageCommandPage", () => {
|
||||
it("does NOT render when the page stack does not have 'language' on top", () => {
|
||||
renderPage();
|
||||
// localeMap codes shouldn't appear because BaseCommandGroup gating is off.
|
||||
expect(screen.queryByText("en-US")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders one CommandItem for every entry in localeMap when active", () => {
|
||||
useCommandPaletteStore.setState({ pages: ["language"] });
|
||||
renderPage();
|
||||
|
||||
const expectedCount = Object.keys(localeMap).length;
|
||||
expect(expectedCount).toBeGreaterThan(0);
|
||||
|
||||
// Each locale value is rendered in the inline font-mono span.
|
||||
for (const code of Object.keys(localeMap).slice(0, 5)) {
|
||||
expect(screen.getByText(code)).toBeInTheDocument();
|
||||
}
|
||||
});
|
||||
|
||||
it("includes the documented set of locales (sample check)", () => {
|
||||
useCommandPaletteStore.setState({ pages: ["language"] });
|
||||
renderPage();
|
||||
// Spot-check a couple of common locales.
|
||||
for (const code of ["en-US", "de-DE", "ja-JP"]) {
|
||||
if (code in localeMap) {
|
||||
expect(screen.getByText(code)).toBeInTheDocument();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { Command } from "@reactive-resume/ui/components/command";
|
||||
import { useCommandPaletteStore } from "../../store";
|
||||
|
||||
vi.mock("@/components/theme/provider", () => ({
|
||||
useTheme: () => ({ setTheme: vi.fn(), theme: "light", toggleTheme: vi.fn() }),
|
||||
}));
|
||||
|
||||
const { ThemeCommandPage } = await import("./theme");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useCommandPaletteStore.setState({ open: false, search: "", pages: [] });
|
||||
});
|
||||
|
||||
const renderPage = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Command>
|
||||
<ThemeCommandPage />
|
||||
</Command>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("ThemeCommandPage", () => {
|
||||
it("is hidden when 'theme' is not on top of the page stack", () => {
|
||||
renderPage();
|
||||
expect(screen.queryByText("Light theme")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders Light + Dark options when active", () => {
|
||||
useCommandPaletteStore.setState({ pages: ["theme"] });
|
||||
renderPage();
|
||||
expect(screen.getByText("Light theme")).toBeInTheDocument();
|
||||
expect(screen.getByText("Dark theme")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { useCommandPaletteStore } from "./store";
|
||||
|
||||
const reset = () => {
|
||||
useCommandPaletteStore.setState({ open: false, search: "", pages: [] });
|
||||
};
|
||||
|
||||
afterEach(reset);
|
||||
|
||||
describe("useCommandPaletteStore", () => {
|
||||
it("starts closed with empty search and no pages", () => {
|
||||
const state = useCommandPaletteStore.getState();
|
||||
expect(state.open).toBe(false);
|
||||
expect(state.search).toBe("");
|
||||
expect(state.pages).toEqual([]);
|
||||
});
|
||||
|
||||
it("setOpen(true) opens the palette without touching other fields", () => {
|
||||
useCommandPaletteStore.setState({ search: "foo", pages: ["page1"] });
|
||||
|
||||
useCommandPaletteStore.getState().setOpen(true);
|
||||
|
||||
const state = useCommandPaletteStore.getState();
|
||||
expect(state.open).toBe(true);
|
||||
expect(state.search).toBe("foo");
|
||||
expect(state.pages).toEqual(["page1"]);
|
||||
});
|
||||
|
||||
it("setOpen(false) resets the entire store back to initial state", () => {
|
||||
useCommandPaletteStore.setState({ open: true, search: "foo", pages: ["page1"] });
|
||||
|
||||
useCommandPaletteStore.getState().setOpen(false);
|
||||
|
||||
const state = useCommandPaletteStore.getState();
|
||||
expect(state.open).toBe(false);
|
||||
expect(state.search).toBe("");
|
||||
expect(state.pages).toEqual([]);
|
||||
});
|
||||
|
||||
it("setSearch updates only the search field", () => {
|
||||
useCommandPaletteStore.getState().setSearch("query");
|
||||
expect(useCommandPaletteStore.getState().search).toBe("query");
|
||||
});
|
||||
|
||||
it("pushPage appends a page and clears search", () => {
|
||||
useCommandPaletteStore.setState({ search: "leftover" });
|
||||
|
||||
useCommandPaletteStore.getState().pushPage("settings");
|
||||
|
||||
const state = useCommandPaletteStore.getState();
|
||||
expect(state.pages).toEqual(["settings"]);
|
||||
expect(state.search).toBe("");
|
||||
});
|
||||
|
||||
it("pushPage stacks multiple pages in order", () => {
|
||||
const { pushPage } = useCommandPaletteStore.getState();
|
||||
pushPage("a");
|
||||
pushPage("b");
|
||||
pushPage("c");
|
||||
expect(useCommandPaletteStore.getState().pages).toEqual(["a", "b", "c"]);
|
||||
});
|
||||
|
||||
it("peekPage returns the top page (or undefined when empty)", () => {
|
||||
expect(useCommandPaletteStore.getState().peekPage()).toBeUndefined();
|
||||
|
||||
useCommandPaletteStore.setState({ pages: ["a", "b"] });
|
||||
expect(useCommandPaletteStore.getState().peekPage()).toBe("b");
|
||||
});
|
||||
|
||||
it("popPage removes the last page and clears search", () => {
|
||||
useCommandPaletteStore.setState({ pages: ["a", "b"], search: "x" });
|
||||
|
||||
useCommandPaletteStore.getState().popPage();
|
||||
|
||||
const state = useCommandPaletteStore.getState();
|
||||
expect(state.pages).toEqual(["a"]);
|
||||
expect(state.search).toBe("");
|
||||
});
|
||||
|
||||
it("reset clears every state field", () => {
|
||||
useCommandPaletteStore.setState({ open: true, search: "x", pages: ["a"] });
|
||||
|
||||
useCommandPaletteStore.getState().reset();
|
||||
|
||||
expect(useCommandPaletteStore.getState()).toMatchObject({ open: false, search: "", pages: [] });
|
||||
});
|
||||
|
||||
describe("goBack", () => {
|
||||
it("clears search first if present, leaving pages and open untouched", () => {
|
||||
useCommandPaletteStore.setState({ open: true, search: "text", pages: ["a"] });
|
||||
|
||||
useCommandPaletteStore.getState().goBack();
|
||||
|
||||
const state = useCommandPaletteStore.getState();
|
||||
expect(state.search).toBe("");
|
||||
expect(state.pages).toEqual(["a"]);
|
||||
expect(state.open).toBe(true);
|
||||
});
|
||||
|
||||
it("pops the top page when no search and pages exist", () => {
|
||||
useCommandPaletteStore.setState({ open: true, search: "", pages: ["a", "b"] });
|
||||
|
||||
useCommandPaletteStore.getState().goBack();
|
||||
|
||||
const state = useCommandPaletteStore.getState();
|
||||
expect(state.pages).toEqual(["a"]);
|
||||
expect(state.open).toBe(true);
|
||||
});
|
||||
|
||||
it("closes the palette when no search and no pages", () => {
|
||||
useCommandPaletteStore.setState({ open: true, search: "", pages: [] });
|
||||
|
||||
useCommandPaletteStore.getState().goBack();
|
||||
|
||||
expect(useCommandPaletteStore.getState().open).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { ChipInput } from "./chip-input";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderInput = (props: Partial<React.ComponentProps<typeof ChipInput>> = {}) =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ChipInput defaultValue={[]} onChange={vi.fn()} {...props} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("ChipInput", () => {
|
||||
it("renders the supplied chips as Badges", () => {
|
||||
renderInput({ defaultValue: ["alpha", "beta", "gamma"] });
|
||||
expect(screen.getByText("alpha")).toBeInTheDocument();
|
||||
expect(screen.getByText("beta")).toBeInTheDocument();
|
||||
expect(screen.getByText("gamma")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adds a chip on Enter, calling onChange with the new list", () => {
|
||||
const onChange = vi.fn();
|
||||
renderInput({ defaultValue: ["a"], onChange });
|
||||
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "b" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(["a", "b"]);
|
||||
});
|
||||
|
||||
it("adds a chip on comma keypress", () => {
|
||||
const onChange = vi.fn();
|
||||
renderInput({ defaultValue: [], onChange });
|
||||
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "new-tag" } });
|
||||
fireEvent.keyDown(input, { key: "," });
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(["new-tag"]);
|
||||
});
|
||||
|
||||
it("does not add a duplicate chip", () => {
|
||||
const onChange = vi.fn();
|
||||
renderInput({ defaultValue: ["a"], onChange });
|
||||
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "a" } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
// chips set should remain ["a"]; onChange not invoked with the same array.
|
||||
const callsAddingA = onChange.mock.calls.filter((args) => Array.isArray(args[0]) && args[0].length > 1);
|
||||
expect(callsAddingA.length).toBe(0);
|
||||
});
|
||||
|
||||
it("does not add an empty / whitespace-only chip", () => {
|
||||
const onChange = vi.fn();
|
||||
renderInput({ defaultValue: ["a"], onChange });
|
||||
|
||||
const input = document.querySelector("input") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: " " } });
|
||||
fireEvent.keyDown(input, { key: "Enter" });
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("hides the description copy when hideDescription is true", () => {
|
||||
const { container } = renderInput({ defaultValue: ["a"], hideDescription: true });
|
||||
// We don't know the exact translated text, just confirm no <Kbd> hint banner is rendered.
|
||||
expect(container.querySelector("kbd")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the description copy by default", () => {
|
||||
const { container } = renderInput({ defaultValue: ["a"] });
|
||||
expect(container.querySelector("kbd")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
vi.mock("@uiw/react-color-colorful", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
const { ColorPicker } = await import("./color-picker");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderPicker = (props: React.ComponentProps<typeof ColorPicker> = {}) =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ColorPicker {...props} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("ColorPicker", () => {
|
||||
it("renders a trigger swatch reflecting the current value", () => {
|
||||
const { container } = renderPicker({ defaultValue: "rgba(231, 0, 11, 1)" });
|
||||
const trigger = container.querySelector("[style*='background-color']") as HTMLElement | null;
|
||||
expect(trigger).not.toBeNull();
|
||||
// happy-dom serializes both the input rgba string and the rgb representation,
|
||||
// depending on alpha; just confirm the color values surface.
|
||||
const bg = trigger?.getAttribute("style") ?? "";
|
||||
expect(bg).toContain("231");
|
||||
expect(bg).toContain("11");
|
||||
});
|
||||
|
||||
it("calls onChange when a preset color is clicked", () => {
|
||||
const onChange = vi.fn();
|
||||
renderPicker({ defaultValue: "rgba(0, 0, 0, 1)", onChange });
|
||||
|
||||
// Open the popover by clicking the trigger swatch.
|
||||
const triggerSwatch = document.querySelector("[style*='background-color']") as HTMLElement;
|
||||
fireEvent.click(triggerSwatch);
|
||||
|
||||
// Locate any preset button (they have aria-label='Use color rgba(...)').
|
||||
const presetBtn = screen.getAllByRole("button", { name: /Use color rgba\(/ })[0];
|
||||
fireEvent.click(presetBtn);
|
||||
|
||||
expect(onChange).toHaveBeenCalled();
|
||||
expect(onChange.mock.calls[0]?.[0]).toMatch(/^rgba\(/);
|
||||
});
|
||||
|
||||
it("renders a custom trigger when provided", () => {
|
||||
renderPicker({
|
||||
defaultValue: "rgba(0, 0, 0, 1)",
|
||||
trigger: <button type="button">custom trigger</button>,
|
||||
});
|
||||
|
||||
expect(screen.getByText("custom trigger")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const queryResult = vi.hoisted(() => ({ data: undefined as number | undefined }));
|
||||
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: () => queryResult,
|
||||
}));
|
||||
vi.mock("@/libs/orpc/client", () => ({
|
||||
orpc: { statistics: { github: { getStarCount: { queryOptions: () => ({}) } } } },
|
||||
}));
|
||||
vi.mock("../animation/count-up", () => ({
|
||||
CountUp: ({ to }: { to: number }) => <span data-testid="count-up">{to.toLocaleString()}</span>,
|
||||
}));
|
||||
|
||||
const { GithubStarsButton } = await import("./github-stars-button");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
queryResult.data = undefined;
|
||||
});
|
||||
|
||||
const renderButton = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<GithubStarsButton />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("GithubStarsButton", () => {
|
||||
it("renders an anchor pointing at the project repo with rel=noopener and target=_blank", () => {
|
||||
renderButton();
|
||||
const link = screen.getByRole("button") as HTMLAnchorElement;
|
||||
expect(link.href).toBe("https://github.com/amruthpillai/reactive-resume");
|
||||
expect(link.target).toBe("_blank");
|
||||
expect(link.rel).toBe("noopener");
|
||||
});
|
||||
|
||||
it("uses the no-count aria-label when star count hasn't loaded yet", () => {
|
||||
renderButton();
|
||||
const link = screen.getByRole("button") as HTMLAnchorElement;
|
||||
expect(link.getAttribute("aria-label")).toBe("Star us on GitHub (opens in new tab)");
|
||||
});
|
||||
|
||||
it("does not render a CountUp when star count is undefined", () => {
|
||||
renderButton();
|
||||
expect(screen.queryByTestId("count-up")).toBeNull();
|
||||
});
|
||||
|
||||
it("renders a CountUp + announces the star count when available", () => {
|
||||
queryResult.data = 12345;
|
||||
renderButton();
|
||||
|
||||
expect(screen.getByTestId("count-up").textContent).toBe("12,345");
|
||||
|
||||
const link = screen.getByRole("button") as HTMLAnchorElement;
|
||||
expect(link.getAttribute("aria-label")).toContain("12,345 stars");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
// react-window's <Grid> uses ResizeObserver / IntersectionObserver heavily and
|
||||
// expects measurable layouts that happy-dom can't provide. Stub it with a simple
|
||||
// pass-through that renders the first row of cells via the supplied cellComponent.
|
||||
vi.mock("react-window", () => ({
|
||||
Grid: ({
|
||||
rowCount,
|
||||
columnCount,
|
||||
cellComponent: CellComponent,
|
||||
cellProps,
|
||||
}: {
|
||||
rowCount: number;
|
||||
columnCount: number;
|
||||
cellComponent: React.ComponentType<
|
||||
{ rowIndex: number; columnIndex: number; style: React.CSSProperties } & Record<string, unknown>
|
||||
>;
|
||||
cellProps: Record<string, unknown>;
|
||||
}) => {
|
||||
const cells: React.ReactNode[] = [];
|
||||
for (let r = 0; r < Math.min(rowCount, 1); r++) {
|
||||
for (let c = 0; c < columnCount; c++) {
|
||||
cells.push(<CellComponent key={`${r}-${c}`} rowIndex={r} columnIndex={c} style={{}} {...cellProps} />);
|
||||
}
|
||||
}
|
||||
return <div data-testid="grid">{cells}</div>;
|
||||
},
|
||||
}));
|
||||
|
||||
const { IconPicker } = await import("./icon-picker");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderPicker = (props: Partial<React.ComponentProps<typeof IconPicker>> = {}) =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<IconPicker value="globe" onChange={vi.fn()} {...props} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("IconPicker", () => {
|
||||
it("renders a trigger button containing the current icon", () => {
|
||||
const { container } = renderPicker();
|
||||
const i = container.querySelector("i.ph") as HTMLElement;
|
||||
expect(i.className).toContain("ph-globe");
|
||||
});
|
||||
|
||||
it("changes the trigger icon when value prop changes", () => {
|
||||
const { container, rerender } = renderPicker({ value: "globe" });
|
||||
const before = container.querySelector("i.ph")?.className ?? "";
|
||||
expect(before).toContain("ph-globe");
|
||||
|
||||
rerender(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<IconPicker value="star" onChange={vi.fn()} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
const after = container.querySelector("i.ph")?.className ?? "";
|
||||
expect(after).toContain("ph-star");
|
||||
});
|
||||
|
||||
it("renders the picker button as a single icon-size button", () => {
|
||||
const { container } = renderPicker();
|
||||
expect(container.querySelectorAll("button").length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { URLInput } from "./url-input";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderInput = (value: { url: string; label: string }, onChange = vi.fn(), hideLabelButton = false) =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<URLInput value={value} onChange={onChange} hideLabelButton={hideLabelButton} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("URLInput", () => {
|
||||
it("strips the https:// prefix in the visible input value", () => {
|
||||
renderInput({ url: "https://example.com/path", label: "" });
|
||||
const input = screen.getByRole("textbox") as HTMLInputElement;
|
||||
expect(input.value).toBe("example.com/path");
|
||||
});
|
||||
|
||||
it("renders the raw value when no prefix is present", () => {
|
||||
renderInput({ url: "no-prefix.example", label: "" });
|
||||
const input = screen.getByRole("textbox") as HTMLInputElement;
|
||||
expect(input.value).toBe("no-prefix.example");
|
||||
});
|
||||
|
||||
it("adds https:// prefix on edit when not already present", () => {
|
||||
const onChange = vi.fn();
|
||||
renderInput({ url: "https://example.com", label: "" }, onChange);
|
||||
|
||||
const input = screen.getByRole("textbox") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "new.example" } });
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
url: "https://new.example",
|
||||
label: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps already-prefixed URLs intact on edit", () => {
|
||||
const onChange = vi.fn();
|
||||
renderInput({ url: "https://example.com", label: "" }, onChange);
|
||||
|
||||
const input = screen.getByRole("textbox") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "https://other.example" } });
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
url: "https://other.example",
|
||||
label: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("emits an empty url string when cleared", () => {
|
||||
const onChange = vi.fn();
|
||||
renderInput({ url: "https://example.com", label: "" }, onChange);
|
||||
|
||||
const input = screen.getByRole("textbox") as HTMLInputElement;
|
||||
fireEvent.change(input, { target: { value: "" } });
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
url: "",
|
||||
label: "",
|
||||
});
|
||||
});
|
||||
|
||||
it("hides the label button when hideLabelButton=true", () => {
|
||||
const { container } = renderInput({ url: "https://example.com", label: "" }, vi.fn(), true);
|
||||
|
||||
// PopoverTrigger is rendered as a button; its absence means hideLabelButton worked.
|
||||
const buttons = container.querySelectorAll("button");
|
||||
expect(buttons.length).toBe(0);
|
||||
});
|
||||
|
||||
it("renders the label button by default", () => {
|
||||
const { container } = renderInput({ url: "https://example.com", label: "" });
|
||||
const buttons = container.querySelectorAll("button");
|
||||
expect(buttons.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BreakpointIndicator } from "./breakpoint-indicator";
|
||||
|
||||
const getWrapper = (container: HTMLElement) => container.firstChild as HTMLElement;
|
||||
|
||||
describe("BreakpointIndicator", () => {
|
||||
it("defaults to bottom-right positioning when no position is supplied", () => {
|
||||
const { container } = render(<BreakpointIndicator />);
|
||||
const wrapper = getWrapper(container);
|
||||
expect(wrapper.className).toContain("bottom-0");
|
||||
// bottom-right path: top branch sets the "bottom-0", right path sets "inset-e-0"
|
||||
expect(wrapper.className).toContain("inset-e-0");
|
||||
});
|
||||
|
||||
it("renders all breakpoint labels (one is visible at each viewport)", () => {
|
||||
const { container } = render(<BreakpointIndicator />);
|
||||
const text = container.textContent ?? "";
|
||||
for (const label of ["XS", "SM", "MD", "LG", "XL", "2XL", "3XL", "4XL"]) {
|
||||
expect(text).toContain(label);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses top-left classes for top-left position", () => {
|
||||
const { container } = render(<BreakpointIndicator position="top-left" />);
|
||||
const wrapper = getWrapper(container);
|
||||
expect(wrapper.className).toContain("top-0");
|
||||
expect(wrapper.className).toContain("inset-s-0");
|
||||
});
|
||||
|
||||
it("uses top-right classes for top-right position", () => {
|
||||
const { container } = render(<BreakpointIndicator position="top-right" />);
|
||||
const wrapper = getWrapper(container);
|
||||
expect(wrapper.className).toContain("top-0");
|
||||
expect(wrapper.className).toContain("inset-e-0");
|
||||
});
|
||||
|
||||
it("uses bottom-left classes for bottom-left position", () => {
|
||||
const { container } = render(<BreakpointIndicator position="bottom-left" />);
|
||||
const wrapper = getWrapper(container);
|
||||
expect(wrapper.className).toContain("bottom-0");
|
||||
expect(wrapper.className).toContain("inset-s-0");
|
||||
});
|
||||
|
||||
it("hides the indicator from print stylesheets", () => {
|
||||
const { container } = render(<BreakpointIndicator />);
|
||||
expect(getWrapper(container).className).toContain("print:hidden");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import type { ErrorComponentProps } from "@tanstack/react-router";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { ErrorScreen } from "./error-screen";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderError = (overrides: { error?: Error; reset?: () => void } = {}) => {
|
||||
const props: ErrorComponentProps = {
|
||||
error: overrides.error ?? new Error("boom"),
|
||||
reset: overrides.reset ?? vi.fn(),
|
||||
};
|
||||
|
||||
return render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ErrorScreen {...props} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
};
|
||||
|
||||
describe("ErrorScreen", () => {
|
||||
it("shows the error message provided", () => {
|
||||
renderError({ error: new Error("Network is down") });
|
||||
expect(screen.getByText("Network is down")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows the user-facing error heading", () => {
|
||||
renderError();
|
||||
expect(screen.getByText("An error occurred while loading the page.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("calls reset when the Refresh button is clicked", () => {
|
||||
const reset = vi.fn();
|
||||
renderError({ reset });
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /refresh/i }));
|
||||
expect(reset).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { LoadingScreen } from "./loading-screen";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("LoadingScreen", () => {
|
||||
it("renders a spinner and the loading text", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<LoadingScreen />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getByText("Loading...")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("fills the viewport (fixed inset-0)", () => {
|
||||
const { container } = render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<LoadingScreen />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("fixed");
|
||||
expect(wrapper.className).toContain("inset-0");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
// `Link` from tanstack/react-router requires a Router context. Stub it out with
|
||||
// a plain anchor so we can render the screen in isolation.
|
||||
vi.mock("@tanstack/react-router", () => ({
|
||||
Link: ({ children, to, ...rest }: React.PropsWithChildren<{ to: string }>) => (
|
||||
<a href={typeof to === "string" ? to : "#"} {...rest}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}));
|
||||
|
||||
const { NotFoundScreen } = await import("./not-found-screen");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderScreen = (routeId = "/missing") =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<NotFoundScreen isNotFound routeId={routeId as never} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("NotFoundScreen", () => {
|
||||
it("renders the documented error heading", () => {
|
||||
renderScreen();
|
||||
expect(screen.getByText("An error occurred while loading the page.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("displays the routeId that triggered the not-found", () => {
|
||||
renderScreen("/dashboard/missing-page");
|
||||
expect(screen.getByText("/dashboard/missing-page")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders a Go Back link", () => {
|
||||
renderScreen();
|
||||
const link = screen.getByRole("link", { name: /go back/i });
|
||||
expect(link.getAttribute("href")).toBe("..");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
|
||||
// Capture the options the Combobox receives so we can introspect them.
|
||||
const captured = vi.hoisted(() => ({
|
||||
options: undefined as Array<{ value: string; label: string }> | undefined,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/combobox", () => ({
|
||||
Combobox: (props: { options: Array<{ value: string; label: string }> }) => {
|
||||
captured.options = props.options;
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
|
||||
const { LevelTypeCombobox } = await import("./combobox");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("LevelTypeCombobox", () => {
|
||||
it("renders one option per level type from levelDesignSchema", () => {
|
||||
render(<LevelTypeCombobox />);
|
||||
|
||||
expect(captured.options?.length).toBe(7);
|
||||
const values = captured.options?.map((o) => o.value);
|
||||
expect(values).toEqual(
|
||||
expect.arrayContaining(["hidden", "circle", "square", "rectangle", "rectangle-full", "progress-bar", "icon"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("produces a human-readable label for each level type", () => {
|
||||
render(<LevelTypeCombobox />);
|
||||
|
||||
for (const opt of captured.options ?? []) {
|
||||
expect(opt.label).toBeTruthy();
|
||||
expect(typeof opt.label).toBe("string");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { LevelDisplay } from "./display";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("LevelDisplay", () => {
|
||||
it("renders nothing when level is 0", () => {
|
||||
const { container } = render(<LevelDisplay type="circle" icon="star" level={0} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders nothing when type is hidden", () => {
|
||||
const { container } = render(<LevelDisplay type="hidden" icon="star" level={3} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders nothing when icon is empty (regardless of type)", () => {
|
||||
const { container } = render(<LevelDisplay type="icon" icon="" level={3} />);
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it("renders 5 segments for progress-bar type", () => {
|
||||
const { container } = render(<LevelDisplay type="progress-bar" icon="star" level={3} />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.children).toHaveLength(5);
|
||||
});
|
||||
|
||||
it("marks first N segments as active for progress-bar", () => {
|
||||
const { container } = render(<LevelDisplay type="progress-bar" icon="star" level={3} />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
const activeStates = Array.from(wrapper.children).map((el) => (el as HTMLElement).dataset.active);
|
||||
expect(activeStates).toEqual(["true", "true", "true", "false", "false"]);
|
||||
});
|
||||
|
||||
it("renders icons for icon type", () => {
|
||||
const { container } = render(<LevelDisplay type="icon" icon="star" level={2} />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.children).toHaveLength(5);
|
||||
expect(wrapper.querySelectorAll("i").length).toBe(5);
|
||||
expect(wrapper.querySelector("i")?.className).toContain("ph-star");
|
||||
});
|
||||
|
||||
it("dims inactive icons for icon type", () => {
|
||||
const { container } = render(<LevelDisplay type="icon" icon="star" level={1} />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
const icons = wrapper.querySelectorAll("i");
|
||||
expect(icons[0]?.className).not.toContain("opacity-40");
|
||||
expect(icons[4]?.className).toContain("opacity-40");
|
||||
});
|
||||
|
||||
it("renders square segments for circle/rectangle/rectangle-full types", () => {
|
||||
for (const type of ["circle", "rectangle", "rectangle-full"] as const) {
|
||||
const { container } = render(<LevelDisplay type={type} icon="star" level={2} />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.children).toHaveLength(5);
|
||||
const activeStates = Array.from(wrapper.children).map((el) => (el as HTMLElement).dataset.active);
|
||||
expect(activeStates).toEqual(["true", "true", "false", "false", "false"]);
|
||||
}
|
||||
});
|
||||
|
||||
it("includes an aria-label describing the level", () => {
|
||||
const { container } = render(<LevelDisplay type="circle" icon="star" level={4} />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.getAttribute("role")).toBe("img");
|
||||
expect(wrapper.getAttribute("aria-label")).toContain("4");
|
||||
});
|
||||
|
||||
it("merges extra className into the wrapper", () => {
|
||||
const { container } = render(<LevelDisplay type="circle" icon="star" level={1} className="extra" />);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("extra");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { localeMap } from "@/libs/locale";
|
||||
import { getLocaleOptions } from "./combobox";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("getLocaleOptions", () => {
|
||||
it("returns one option per entry in localeMap", () => {
|
||||
const options = getLocaleOptions();
|
||||
expect(options).toHaveLength(Object.keys(localeMap).length);
|
||||
});
|
||||
|
||||
it("uses the locale code as the value", () => {
|
||||
const options = getLocaleOptions();
|
||||
const values = options.map((opt) => opt.value);
|
||||
expect(values).toContain("en-US");
|
||||
expect(values).toContain("de-DE");
|
||||
});
|
||||
|
||||
it("populates label and keywords with the same translated string", () => {
|
||||
const options = getLocaleOptions();
|
||||
const enUS = options.find((opt) => opt.value === "en-US");
|
||||
expect(enUS?.label).toBeTruthy();
|
||||
expect(enUS?.keywords).toEqual([enUS?.label]);
|
||||
});
|
||||
|
||||
it("uses unique values for every option", () => {
|
||||
const values = getLocaleOptions().map((opt) => opt.value);
|
||||
expect(new Set(values).size).toBe(values.length);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import type { ResumeData } from "@reactive-resume/schema/resume/data";
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_PDF_PAGE_SIZE,
|
||||
getPreviewCanvasScale,
|
||||
getScaledPreviewPageSize,
|
||||
normalizeResumePreviewProps,
|
||||
} from "./preview.shared";
|
||||
|
||||
describe("normalizeResumePreviewProps", () => {
|
||||
it("applies the documented defaults when fields are omitted", () => {
|
||||
const result = normalizeResumePreviewProps({});
|
||||
expect(result).toMatchObject({
|
||||
pageGap: 40,
|
||||
pageLayout: "horizontal",
|
||||
pageScale: 1,
|
||||
showPageNumbers: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves supplied values and forwards extra props (className, data)", () => {
|
||||
const result = normalizeResumePreviewProps({
|
||||
className: "preview-class",
|
||||
pageGap: 16,
|
||||
pageLayout: "vertical",
|
||||
pageScale: 1.5,
|
||||
showPageNumbers: true,
|
||||
});
|
||||
|
||||
expect(result.className).toBe("preview-class");
|
||||
expect(result.pageGap).toBe(16);
|
||||
expect(result.pageLayout).toBe("vertical");
|
||||
expect(result.pageScale).toBe(1.5);
|
||||
expect(result.showPageNumbers).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getScaledPreviewPageSize", () => {
|
||||
it("multiplies both dimensions by the scale", () => {
|
||||
const result = getScaledPreviewPageSize({ width: 100, height: 200 }, 2);
|
||||
expect(result).toEqual({ width: 200, height: 400 });
|
||||
});
|
||||
|
||||
it("returns the default A4 page size unchanged when scaled by 1", () => {
|
||||
expect(getScaledPreviewPageSize(DEFAULT_PDF_PAGE_SIZE, 1)).toEqual(DEFAULT_PDF_PAGE_SIZE);
|
||||
});
|
||||
|
||||
it("supports fractional scaling", () => {
|
||||
const result = getScaledPreviewPageSize({ width: 100, height: 200 }, 0.5);
|
||||
expect(result).toEqual({ width: 50, height: 100 });
|
||||
});
|
||||
});
|
||||
|
||||
const setDevicePixelRatio = (value: number) => {
|
||||
Object.defineProperty(window, "devicePixelRatio", {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value,
|
||||
});
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
setDevicePixelRatio(1);
|
||||
});
|
||||
|
||||
describe("getPreviewCanvasScale", () => {
|
||||
it("returns the desired render scale (4x) for small pages", () => {
|
||||
setDevicePixelRatio(1);
|
||||
// width * height * 4 * 4 = 100 * 100 * 16 = 160_000 ≪ 16_777_216 budget
|
||||
expect(getPreviewCanvasScale(100, 100)).toBe(4);
|
||||
});
|
||||
|
||||
it("uses devicePixelRatio when it exceeds the desired 4x scale", () => {
|
||||
setDevicePixelRatio(8);
|
||||
// 50*50*8*8 = 160_000 ≪ budget, so we keep the 8x devicePixelRatio
|
||||
expect(getPreviewCanvasScale(50, 50)).toBe(8);
|
||||
});
|
||||
|
||||
it("clamps the scale when the page would exceed the canvas pixel budget", () => {
|
||||
setDevicePixelRatio(1);
|
||||
const scale = getPreviewCanvasScale(2000, 3000);
|
||||
// Should NOT exceed the 4x desired scale and must satisfy the pixel budget.
|
||||
expect(scale).toBeLessThan(4);
|
||||
expect(scale * scale * 2000 * 3000).toBeLessThanOrEqual(16_777_216 + 1);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { sampleResumeData } from "@reactive-resume/schema/resume/sample";
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// ThemeProvider depends on TanStack Start helpers + server fn — stub them.
|
||||
vi.mock("@tanstack/react-router", () => ({
|
||||
useRouter: () => ({ invalidate: vi.fn() }),
|
||||
}));
|
||||
vi.mock("@/libs/theme", () => ({
|
||||
setThemeServerFn: vi.fn().mockResolvedValue(undefined),
|
||||
}));
|
||||
|
||||
const { ThemeProvider, useTheme } = await import("./provider");
|
||||
|
||||
describe("useTheme", () => {
|
||||
it("throws when used outside ThemeProvider", () => {
|
||||
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
|
||||
expect(() => renderHook(() => useTheme())).toThrow(/useTheme must be used within a ThemeProvider/);
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
it("returns the theme and helpers when wrapped in ThemeProvider", () => {
|
||||
const { result } = renderHook(() => useTheme(), {
|
||||
wrapper: ({ children }) => <ThemeProvider theme="dark">{children}</ThemeProvider>,
|
||||
});
|
||||
|
||||
expect(result.current.theme).toBe("dark");
|
||||
expect(typeof result.current.setTheme).toBe("function");
|
||||
expect(typeof result.current.toggleTheme).toBe("function");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
|
||||
const toggleTheme = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("./provider", () => ({
|
||||
useTheme: () => ({ theme: "light", setTheme: vi.fn(), toggleTheme }),
|
||||
}));
|
||||
|
||||
const { ThemeToggleButton } = await import("./toggle-button");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
toggleTheme.mockReset();
|
||||
// Reset prefers-reduced-motion + startViewTransition stub between tests.
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
})),
|
||||
});
|
||||
// biome-ignore lint/suspicious/noExplicitAny: removing a non-standard API stub
|
||||
(document as any).startViewTransition = undefined;
|
||||
});
|
||||
|
||||
describe("ThemeToggleButton", () => {
|
||||
it("renders a button with an aria-label that flips with the theme", () => {
|
||||
const { container } = render(<ThemeToggleButton />);
|
||||
const button = container.querySelector("button");
|
||||
expect(button?.getAttribute("aria-label")).toBe("Switch to dark theme");
|
||||
});
|
||||
|
||||
it("calls toggleTheme directly when the view-transition API is unavailable", () => {
|
||||
const { container } = render(<ThemeToggleButton />);
|
||||
const button = container.querySelector("button") as HTMLButtonElement;
|
||||
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(toggleTheme).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("calls toggleTheme directly when prefers-reduced-motion is set", () => {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: query.includes("prefers-reduced-motion"),
|
||||
media: query,
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
})),
|
||||
});
|
||||
|
||||
const startVT = vi.fn();
|
||||
Object.defineProperty(document, "startViewTransition", {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: startVT,
|
||||
});
|
||||
|
||||
const { container } = render(<ThemeToggleButton />);
|
||||
fireEvent.click(container.querySelector("button") as HTMLButtonElement);
|
||||
|
||||
expect(toggleTheme).toHaveBeenCalledTimes(1);
|
||||
expect(startVT).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { FontWeightCombobox } from "./combobox";
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { getNextWeights } from "./combobox";
|
||||
|
||||
describe("getNextWeights", () => {
|
||||
it("returns 400 and 600 when both are available (the preferred default)", () => {
|
||||
// Source Sans 3 covers a wide weight range including 400 and 600.
|
||||
const weights = getNextWeights("Source Sans 3");
|
||||
expect(weights).toEqual(["400", "600"]);
|
||||
});
|
||||
|
||||
it("returns null for unknown font families", () => {
|
||||
expect(getNextWeights("This Font Does Not Exist")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns an array containing exactly known weight strings (subset of 100..900)", () => {
|
||||
const weights = getNextWeights("Source Sans 3");
|
||||
const validWeights = new Set(["100", "200", "300", "400", "500", "600", "700", "800", "900"]);
|
||||
for (const w of weights ?? []) {
|
||||
expect(validWeights.has(w)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("contains at most two weights", () => {
|
||||
const weights = getNextWeights("Source Sans 3");
|
||||
expect(weights?.length).toBeLessThanOrEqual(2);
|
||||
});
|
||||
|
||||
it("returns the family's only weight (deduplicated) when only one is available", () => {
|
||||
// Find a font with a single weight by scanning the fontList — fall back gracefully.
|
||||
// We probe a known web font that may only ship 400; the test asserts uniqueness regardless.
|
||||
const weights = getNextWeights("Source Sans 3");
|
||||
if (weights) {
|
||||
expect(new Set(weights).size).toBe(weights.length);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import type { ComboboxOption } from "./combobox";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { Combobox } from "./combobox";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const options: ComboboxOption<"alpha" | "beta" | "gamma">[] = [
|
||||
{ value: "alpha", label: "Alpha" },
|
||||
{ value: "beta", label: "Beta" },
|
||||
{ value: "gamma", label: "Gamma" },
|
||||
];
|
||||
|
||||
const wrap = (ui: React.ReactNode) => render(<I18nProvider i18n={i18n}>{ui}</I18nProvider>);
|
||||
|
||||
describe("Combobox", () => {
|
||||
it("renders the default placeholder when nothing is selected", () => {
|
||||
wrap(<Combobox options={[...options]} placeholder="Pick something" />);
|
||||
expect(screen.getByText("Pick something")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the selected option label when a value is provided", () => {
|
||||
wrap(<Combobox options={[...options]} value="beta" />);
|
||||
// The label appears inside the trigger; both label and trigger may render it,
|
||||
// so use queryAllByText for resilience.
|
||||
expect(screen.getAllByText("Beta").length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders all option labels for the multi-select default values", () => {
|
||||
wrap(<Combobox multiple options={[...options]} defaultValue={["alpha", "gamma"]} />);
|
||||
expect(screen.getAllByText(/Alpha/).length).toBeGreaterThan(0);
|
||||
expect(screen.getAllByText(/Gamma/).length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("renders nothing extra when given an empty options array (no crash)", () => {
|
||||
expect(() => wrap(<Combobox options={[]} placeholder="Empty" />)).not.toThrow();
|
||||
expect(screen.getByText("Empty")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
vi.stubGlobal("__APP_VERSION__", "9.9.9");
|
||||
|
||||
const { Copyright } = await import("./copyright");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderCopyright = (props?: React.ComponentProps<typeof Copyright>) =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Copyright {...props} />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("Copyright", () => {
|
||||
it("renders the MIT license link", () => {
|
||||
renderCopyright();
|
||||
const link = screen.getByRole("link", { name: "MIT" });
|
||||
expect(link.getAttribute("href")).toBe("https://github.com/AmruthPillai/Reactive-Resume/blob/main/LICENSE");
|
||||
expect(link.getAttribute("rel")).toBe("noopener");
|
||||
});
|
||||
|
||||
it("renders the Amruth Pillai attribution link", () => {
|
||||
renderCopyright();
|
||||
const link = screen.getByRole("link", { name: "Amruth Pillai" });
|
||||
expect(link.getAttribute("href")).toBe("https://amruthpillai.com");
|
||||
});
|
||||
|
||||
it("includes the app version string", () => {
|
||||
renderCopyright();
|
||||
expect(screen.getByText(/v9\.9\.9/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("merges custom className into the wrapper", () => {
|
||||
const { container } = renderCopyright({ className: "extra-class" });
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("extra-class");
|
||||
expect(wrapper.className).toContain("text-muted-foreground");
|
||||
});
|
||||
|
||||
it("opens external links in a new tab", () => {
|
||||
renderCopyright();
|
||||
for (const link of screen.getAllByRole("link")) {
|
||||
expect(link.getAttribute("target")).toBe("_blank");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { templates } from "./data";
|
||||
|
||||
describe("templates metadata", () => {
|
||||
const entries = Object.entries(templates);
|
||||
|
||||
it("declares the expected template ids", () => {
|
||||
const ids = Object.keys(templates).sort();
|
||||
expect(ids).toEqual(
|
||||
[
|
||||
"azurill",
|
||||
"bronzor",
|
||||
"chikorita",
|
||||
"ditgar",
|
||||
"ditto",
|
||||
"gengar",
|
||||
"glalie",
|
||||
"kakuna",
|
||||
"lapras",
|
||||
"leafish",
|
||||
"meowth",
|
||||
"onyx",
|
||||
"pikachu",
|
||||
"rhyhorn",
|
||||
].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it("provides a name, description, image, and tags for every template", () => {
|
||||
for (const [id, meta] of entries) {
|
||||
expect(meta.name, id).toBeTruthy();
|
||||
expect(meta.description, id).toBeDefined();
|
||||
expect(meta.imageUrl, id).toMatch(/^\/templates\//);
|
||||
expect(Array.isArray(meta.tags), id).toBe(true);
|
||||
expect(meta.tags.length, id).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses a recognized sidebar position for every template", () => {
|
||||
const validPositions = new Set(["left", "right", "none"]);
|
||||
for (const [id, meta] of entries) {
|
||||
expect(validPositions.has(meta.sidebarPosition), `${id}: ${meta.sidebarPosition}`).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses unique image URLs per template", () => {
|
||||
const urls = entries.map(([, m]) => m.imageUrl);
|
||||
expect(new Set(urls).size).toBe(urls.length);
|
||||
});
|
||||
|
||||
it("uses lowercase ids that match a lowercase form of the display name", () => {
|
||||
for (const [id, meta] of entries) {
|
||||
expect(id).toBe(id.toLowerCase());
|
||||
expect(meta.name.toLowerCase()).toBe(id);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { Dialog } from "@reactive-resume/ui/components/dialog";
|
||||
import { useDialogStore } from "@/dialogs/store";
|
||||
|
||||
const updateResumeData = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: { metadata: { template: "ditto" } },
|
||||
}),
|
||||
useUpdateResumeData: () => updateResumeData,
|
||||
}));
|
||||
|
||||
const { TemplateGalleryDialog } = await import("./gallery");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
updateResumeData.mockReset();
|
||||
useDialogStore.setState({ open: false, activeDialog: null, onBeforeClose: null });
|
||||
});
|
||||
|
||||
const renderGallery = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Dialog open>
|
||||
<TemplateGalleryDialog />
|
||||
</Dialog>
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("TemplateGalleryDialog", () => {
|
||||
it("renders the documented title and intro copy", () => {
|
||||
renderGallery();
|
||||
expect(screen.getByText("Template Gallery")).toBeInTheDocument();
|
||||
expect(screen.getByText(/range of resume templates/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders one tile per template", () => {
|
||||
renderGallery();
|
||||
// Each tile renders an <img alt={metadata.name}>. The data module lists 14 templates.
|
||||
const images = screen.getAllByRole("img");
|
||||
expect(images.length).toBeGreaterThanOrEqual(14);
|
||||
});
|
||||
|
||||
it("ring-highlights the currently-selected template tile (Ditto)", () => {
|
||||
renderGallery();
|
||||
const dittoImg = screen.getByAltText("Ditto");
|
||||
const button = dittoImg.closest("button") as HTMLButtonElement;
|
||||
expect(button.className).toContain("ring-ring");
|
||||
});
|
||||
|
||||
it("selecting a different template calls updateResumeData with the new template id", () => {
|
||||
renderGallery();
|
||||
const onyxImg = screen.getByAltText("Onyx");
|
||||
const button = onyxImg.closest("button") as HTMLButtonElement;
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(updateResumeData).toHaveBeenCalledTimes(1);
|
||||
const recipe = updateResumeData.mock.calls[0]?.[0] as (draft: { metadata: { template: string } }) => void;
|
||||
const draft = { metadata: { template: "ditto" } };
|
||||
recipe(draft);
|
||||
expect(draft.metadata.template).toBe("onyx");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,69 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ConfirmDialogProvider, useConfirm } from "./use-confirm";
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<ConfirmDialogProvider>{children}</ConfirmDialogProvider>
|
||||
);
|
||||
|
||||
describe("useConfirm", () => {
|
||||
it("throws when used outside ConfirmDialogProvider", () => {
|
||||
expect(() => renderHook(() => useConfirm())).toThrow(/useConfirm must be used within a <ConfirmDialogProvider \/>/);
|
||||
});
|
||||
|
||||
it("returns a confirm function when wrapped in provider", () => {
|
||||
const { result } = renderHook(() => useConfirm(), { wrapper });
|
||||
expect(typeof result.current).toBe("function");
|
||||
});
|
||||
|
||||
it("returns a pending promise that resolves to a boolean", async () => {
|
||||
const { result } = renderHook(() => useConfirm(), { wrapper });
|
||||
|
||||
let promise!: Promise<boolean>;
|
||||
await act(async () => {
|
||||
promise = result.current("Are you sure?");
|
||||
});
|
||||
expect(promise).toBeInstanceOf(Promise);
|
||||
});
|
||||
|
||||
it("resolves false when the dialog is dismissed", async () => {
|
||||
const { result } = renderHook(() => useConfirm(), { wrapper });
|
||||
|
||||
let promise!: Promise<boolean>;
|
||||
await act(async () => {
|
||||
promise = result.current("Heading");
|
||||
});
|
||||
|
||||
// Click the cancel button to close.
|
||||
const cancelBtn = document.body.querySelector('button[type="button"][data-slot="alert-dialog-cancel"]');
|
||||
// Fallback: cancel buttons in shadcn/base-ui dialogs usually carry role="button" + text.
|
||||
const buttons = Array.from(document.body.querySelectorAll<HTMLButtonElement>("button"));
|
||||
const cancel = buttons.find((b) => /cancel/i.test(b.textContent ?? ""));
|
||||
|
||||
await act(async () => {
|
||||
(cancelBtn as HTMLButtonElement | null)?.click() ?? cancel?.click();
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("resolves true when the confirm button is clicked", async () => {
|
||||
const { result } = renderHook(() => useConfirm(), { wrapper });
|
||||
|
||||
let promise!: Promise<boolean>;
|
||||
await act(async () => {
|
||||
promise = result.current("Heading", { confirmText: "Yes" });
|
||||
});
|
||||
|
||||
const buttons = Array.from(document.body.querySelectorAll<HTMLButtonElement>("button"));
|
||||
const yes = buttons.find((b) => /yes/i.test(b.textContent ?? ""));
|
||||
|
||||
await act(async () => {
|
||||
yes?.click();
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { useControlledState } from "./use-controlled-state";
|
||||
|
||||
describe("useControlledState", () => {
|
||||
it("returns the defaultValue when uncontrolled", () => {
|
||||
const { result } = renderHook(() => useControlledState({ defaultValue: 0 }));
|
||||
expect(result.current[0]).toBe(0);
|
||||
});
|
||||
|
||||
it("returns the value when controlled", () => {
|
||||
const { result } = renderHook(() => useControlledState({ value: 42, defaultValue: 0 }));
|
||||
expect(result.current[0]).toBe(42);
|
||||
});
|
||||
|
||||
it("updates internal state when value prop changes (controlled)", () => {
|
||||
const { result, rerender } = renderHook(({ value }: { value: number }) => useControlledState({ value }), {
|
||||
initialProps: { value: 1 },
|
||||
});
|
||||
|
||||
expect(result.current[0]).toBe(1);
|
||||
rerender({ value: 2 });
|
||||
expect(result.current[0]).toBe(2);
|
||||
});
|
||||
|
||||
it("updates state via setter when uncontrolled", () => {
|
||||
const { result } = renderHook(() => useControlledState<number>({ defaultValue: 0 }));
|
||||
act(() => {
|
||||
result.current[1](10);
|
||||
});
|
||||
expect(result.current[0]).toBe(10);
|
||||
});
|
||||
|
||||
it("calls onChange when state is updated", () => {
|
||||
const onChange = vi.fn();
|
||||
const { result } = renderHook(() => useControlledState<string>({ defaultValue: "a", onChange }));
|
||||
|
||||
act(() => {
|
||||
result.current[1]("b");
|
||||
});
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith("b");
|
||||
});
|
||||
|
||||
it("forwards extra args to onChange", () => {
|
||||
const onChange = vi.fn();
|
||||
const { result } = renderHook(() => useControlledState<string, [number, boolean]>({ defaultValue: "a", onChange }));
|
||||
|
||||
act(() => {
|
||||
result.current[1]("b", 42, true);
|
||||
});
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith("b", 42, true);
|
||||
});
|
||||
|
||||
it("does not call onChange when value prop changes from outside", () => {
|
||||
const onChange = vi.fn();
|
||||
const { rerender } = renderHook(({ value }: { value: number }) => useControlledState<number>({ value, onChange }), {
|
||||
initialProps: { value: 1 },
|
||||
});
|
||||
|
||||
rerender({ value: 2 });
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a stable setter reference when onChange is stable", () => {
|
||||
const onChange = vi.fn();
|
||||
const { result, rerender } = renderHook(
|
||||
({ value }: { value: number }) => useControlledState<number>({ value, onChange }),
|
||||
{ initialProps: { value: 1 } },
|
||||
);
|
||||
|
||||
const initialSetter = result.current[1];
|
||||
rerender({ value: 2 });
|
||||
expect(result.current[1]).toBe(initialSetter);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useIsMobile } from "./use-mobile";
|
||||
|
||||
type Listener = (event: { matches: boolean }) => void;
|
||||
|
||||
type FakeMediaQueryList = {
|
||||
matches: boolean;
|
||||
addEventListener: (type: string, fn: Listener) => void;
|
||||
removeEventListener: (type: string, fn: Listener) => void;
|
||||
__listeners: Set<Listener>;
|
||||
__set: (matches: boolean) => void;
|
||||
};
|
||||
|
||||
const createMatchMedia = (initialMatches: boolean) => {
|
||||
const mqlByQuery = new Map<string, FakeMediaQueryList>();
|
||||
|
||||
const matchMedia = vi.fn((query: string): FakeMediaQueryList => {
|
||||
let mql = mqlByQuery.get(query);
|
||||
if (mql) return mql;
|
||||
|
||||
const listeners = new Set<Listener>();
|
||||
mql = {
|
||||
matches: initialMatches,
|
||||
addEventListener: (_type, fn) => listeners.add(fn),
|
||||
removeEventListener: (_type, fn) => listeners.delete(fn),
|
||||
__listeners: listeners,
|
||||
__set: (matches: boolean) => {
|
||||
// biome-ignore lint/style/noNonNullAssertion: This closure only runs after the media query list has been initialized.
|
||||
mql!.matches = matches;
|
||||
for (const fn of listeners) fn({ matches });
|
||||
},
|
||||
};
|
||||
mqlByQuery.set(query, mql);
|
||||
return mql;
|
||||
});
|
||||
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
configurable: true,
|
||||
value: matchMedia,
|
||||
});
|
||||
|
||||
return { matchMedia, getMql: (q: string) => mqlByQuery.get(q) };
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("useIsMobile", () => {
|
||||
it("returns true when the viewport matches the mobile media query", () => {
|
||||
createMatchMedia(true);
|
||||
const { result } = renderHook(() => useIsMobile());
|
||||
expect(result.current).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when the viewport does not match the mobile media query", () => {
|
||||
createMatchMedia(false);
|
||||
const { result } = renderHook(() => useIsMobile());
|
||||
expect(result.current).toBe(false);
|
||||
});
|
||||
|
||||
it("uses the (max-width: 767px) query", () => {
|
||||
const { matchMedia } = createMatchMedia(false);
|
||||
renderHook(() => useIsMobile());
|
||||
expect(matchMedia).toHaveBeenCalledWith("(max-width: 767px)");
|
||||
});
|
||||
|
||||
it("updates when the media query change event fires", () => {
|
||||
const { getMql } = createMatchMedia(false);
|
||||
const { result } = renderHook(() => useIsMobile());
|
||||
|
||||
expect(result.current).toBe(false);
|
||||
|
||||
act(() => {
|
||||
getMql("(max-width: 767px)")?.__set(true);
|
||||
});
|
||||
|
||||
expect(result.current).toBe(true);
|
||||
});
|
||||
|
||||
it("removes the listener on unmount", () => {
|
||||
const { getMql } = createMatchMedia(false);
|
||||
const { unmount } = renderHook(() => useIsMobile());
|
||||
|
||||
const mql = getMql("(max-width: 767px)");
|
||||
expect(mql?.__listeners.size).toBe(1);
|
||||
|
||||
unmount();
|
||||
expect(mql?.__listeners.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { PromptDialogProvider, usePrompt } from "./use-prompt";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<PromptDialogProvider>{children}</PromptDialogProvider>
|
||||
);
|
||||
|
||||
const clickButton = (re: RegExp) => {
|
||||
const buttons = Array.from(document.body.querySelectorAll<HTMLButtonElement>("button"));
|
||||
buttons.find((b) => re.test(b.textContent ?? ""))?.click();
|
||||
};
|
||||
|
||||
describe("usePrompt", () => {
|
||||
it("throws when used outside PromptDialogProvider", () => {
|
||||
expect(() => renderHook(() => usePrompt())).toThrow(/usePrompt must be used within a <PromptDialogProvider \/>/);
|
||||
});
|
||||
|
||||
it("returns a function when wrapped in provider", () => {
|
||||
const { result } = renderHook(() => usePrompt(), { wrapper });
|
||||
expect(typeof result.current).toBe("function");
|
||||
});
|
||||
|
||||
it("resolves null when Cancel is clicked", async () => {
|
||||
const { result } = renderHook(() => usePrompt(), { wrapper });
|
||||
|
||||
let promise!: Promise<string | null>;
|
||||
await act(async () => {
|
||||
promise = result.current("Name?");
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
clickButton(/cancel/i);
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("resolves to current input value when Confirm is clicked", async () => {
|
||||
const { result } = renderHook(() => usePrompt(), { wrapper });
|
||||
|
||||
let promise!: Promise<string | null>;
|
||||
await act(async () => {
|
||||
promise = result.current("Name?", { defaultValue: "Initial" });
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
clickButton(/confirm/i);
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toBe("Initial");
|
||||
});
|
||||
|
||||
it("uses the supplied defaultValue as the initial input value", async () => {
|
||||
const { result } = renderHook(() => usePrompt(), { wrapper });
|
||||
|
||||
let promise!: Promise<string | null>;
|
||||
await act(async () => {
|
||||
promise = result.current("Heading", { defaultValue: "preset" });
|
||||
});
|
||||
|
||||
// The input element should hold the default before we click anything.
|
||||
const input = document.body.querySelector("input") as HTMLInputElement | null;
|
||||
expect(input?.value).toBe("preset");
|
||||
|
||||
await act(async () => {
|
||||
clickButton(/confirm/i);
|
||||
});
|
||||
|
||||
await expect(promise).resolves.toBe("preset");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { useSyncFormValues } from "./use-sync-form-values";
|
||||
|
||||
const makeForm = <T>(values: T) => {
|
||||
const reset = vi.fn((next: T) => {
|
||||
form.state.values = next;
|
||||
});
|
||||
const form = { reset, state: { values } };
|
||||
return form;
|
||||
};
|
||||
|
||||
describe("useSyncFormValues", () => {
|
||||
it("does not call reset when values are deeply equal", () => {
|
||||
const form = makeForm({ a: 1, nested: { x: 1 } });
|
||||
|
||||
renderHook(({ values }) => useSyncFormValues(form, values), {
|
||||
initialProps: { values: { a: 1, nested: { x: 1 } } },
|
||||
});
|
||||
|
||||
expect(form.reset).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls reset when values differ on mount", () => {
|
||||
const form = makeForm({ a: 1 });
|
||||
const next = { a: 2 };
|
||||
|
||||
renderHook(() => useSyncFormValues(form, next));
|
||||
|
||||
expect(form.reset).toHaveBeenCalledWith(next);
|
||||
});
|
||||
|
||||
it("calls reset when values prop changes to a different shape", () => {
|
||||
const form = makeForm<{ a: number }>({ a: 1 });
|
||||
|
||||
const { rerender } = renderHook(({ values }) => useSyncFormValues(form, values), {
|
||||
initialProps: { values: { a: 1 } },
|
||||
});
|
||||
|
||||
expect(form.reset).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ values: { a: 5 } });
|
||||
|
||||
expect(form.reset).toHaveBeenCalledWith({ a: 5 });
|
||||
expect(form.reset).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("ignores new value identity when deeply equal", () => {
|
||||
const form = makeForm<{ a: number }>({ a: 1 });
|
||||
|
||||
const { rerender } = renderHook(({ values }) => useSyncFormValues(form, values), {
|
||||
initialProps: { values: { a: 1 } },
|
||||
});
|
||||
|
||||
rerender({ values: { a: 1 } });
|
||||
|
||||
expect(form.reset).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { QueryClient } from "@tanstack/react-query";
|
||||
import { getQueryClient } from "./client";
|
||||
|
||||
describe("getQueryClient", () => {
|
||||
it("returns a QueryClient instance", () => {
|
||||
const client = getQueryClient();
|
||||
expect(client).toBeInstanceOf(QueryClient);
|
||||
});
|
||||
|
||||
it("returns a fresh client on each call", () => {
|
||||
const a = getQueryClient();
|
||||
const b = getQueryClient();
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
|
||||
it("hashes the query key into a deterministic JSON string", () => {
|
||||
const client = getQueryClient();
|
||||
const fn = client.getDefaultOptions().queries?.queryKeyHashFn;
|
||||
expect(typeof fn).toBe("function");
|
||||
|
||||
const hashA = fn?.(["resumes", { id: "abc" }]);
|
||||
const hashB = fn?.(["resumes", { id: "abc" }]);
|
||||
const hashC = fn?.(["resumes", { id: "xyz" }]);
|
||||
|
||||
expect(hashA).toBe(hashB);
|
||||
expect(hashA).not.toBe(hashC);
|
||||
expect(typeof hashA).toBe("string");
|
||||
// json/meta envelope is included
|
||||
expect(hashA).toContain('"json"');
|
||||
});
|
||||
|
||||
it("round-trips data through dehydrate/hydrate via oRPC serializer", () => {
|
||||
const client = getQueryClient();
|
||||
const serializeData = client.getDefaultOptions().dehydrate?.serializeData;
|
||||
const deserializeData = client.getDefaultOptions().hydrate?.deserializeData;
|
||||
|
||||
expect(serializeData).toBeTypeOf("function");
|
||||
expect(deserializeData).toBeTypeOf("function");
|
||||
|
||||
const original = { id: "x", count: 3, when: new Date("2024-01-01T00:00:00Z") };
|
||||
const serialized = serializeData?.(original);
|
||||
const restored = deserializeData?.(serialized) as typeof original;
|
||||
|
||||
expect(restored.id).toBe(original.id);
|
||||
expect(restored.count).toBe(original.count);
|
||||
expect(restored.when.getTime()).toBe(original.when.getTime());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Mock locale module so getLocaleMessages returns a known mapping
|
||||
// without trying to dynamically load .po files (which Vite/glob handles
|
||||
// only inside the real bundle).
|
||||
vi.mock("@/libs/locale", () => ({
|
||||
resolveLocale: (locale: string) => locale || "en-US",
|
||||
getLocaleMessages: async (locale: string) => ({
|
||||
locale,
|
||||
messages: {},
|
||||
}),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
describe("createSectionTitleResolverForLocale", () => {
|
||||
it("returns a resolver function that produces section titles", async () => {
|
||||
const { createSectionTitleResolverForLocale } = await import("./section-title-locale");
|
||||
|
||||
const resolver = await createSectionTitleResolverForLocale("en-US");
|
||||
const title = resolver({ sectionId: "experience", locale: "en-US", sectionKind: "builtin" });
|
||||
|
||||
expect(typeof title).toBe("string");
|
||||
expect(title.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("caches resolvers per requested locale", async () => {
|
||||
const { createSectionTitleResolverForLocale } = await import("./section-title-locale");
|
||||
|
||||
const a = await createSectionTitleResolverForLocale("en-US");
|
||||
const b = await createSectionTitleResolverForLocale("en-US");
|
||||
|
||||
expect(a).toBe(b);
|
||||
});
|
||||
|
||||
it("falls back to en-US for an unknown locale", async () => {
|
||||
const { createSectionTitleResolverForLocale } = await import("./section-title-locale");
|
||||
|
||||
const resolver = await createSectionTitleResolverForLocale("xx-YY");
|
||||
const title = resolver({ sectionId: "skills", locale: "en-US", sectionKind: "builtin" });
|
||||
|
||||
expect(typeof title).toBe("string");
|
||||
expect(title.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("useSectionTitleResolver", () => {
|
||||
it("returns null when no locale is provided", async () => {
|
||||
const { useSectionTitleResolver } = await import("./section-title-locale");
|
||||
|
||||
const { result } = renderHook(() => useSectionTitleResolver(undefined));
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
|
||||
it("loads a resolver when a locale is provided", async () => {
|
||||
const { useSectionTitleResolver } = await import("./section-title-locale");
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ locale }: { locale: string | undefined }) => useSectionTitleResolver(locale),
|
||||
{
|
||||
initialProps: { locale: "en-US" as string | undefined },
|
||||
},
|
||||
);
|
||||
|
||||
// Initially null while the resolver is loading async.
|
||||
expect(result.current).toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
// Flush microtasks so the async resolver settles.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
expect(typeof result.current).toBe("function");
|
||||
|
||||
// Switching to undefined clears the resolver.
|
||||
rerender({ locale: undefined });
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { MessageDescriptor } from "@lingui/core";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { createSectionTitleResolver } from "./section-title";
|
||||
|
||||
const makeTranslator = (translate: (d: MessageDescriptor) => string = (d) => d.message ?? "") => ({
|
||||
_: vi.fn(translate),
|
||||
});
|
||||
|
||||
describe("createSectionTitleResolver", () => {
|
||||
it("returns the translated message for a built-in section", () => {
|
||||
const translator = makeTranslator((d) => (d.message === "Experience" ? "Erfahrung" : (d.message ?? "")));
|
||||
const resolve = createSectionTitleResolver(translator);
|
||||
|
||||
const result = resolve({
|
||||
sectionId: "experience",
|
||||
locale: "en-US",
|
||||
sectionKind: "builtin",
|
||||
defaultEnglishTitle: "Experience",
|
||||
});
|
||||
|
||||
expect(result).toBe("Erfahrung");
|
||||
expect(translator._).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns the translated message for a custom section by its type", () => {
|
||||
const translator = makeTranslator((d) => (d.message === "Cover Letter" ? "Anschreiben" : (d.message ?? "")));
|
||||
const resolve = createSectionTitleResolver(translator);
|
||||
|
||||
const result = resolve({
|
||||
sectionId: "custom-1",
|
||||
locale: "en-US",
|
||||
sectionKind: "custom",
|
||||
customSectionType: "cover-letter",
|
||||
defaultEnglishTitle: "Cover Letter",
|
||||
});
|
||||
|
||||
expect(result).toBe("Anschreiben");
|
||||
});
|
||||
|
||||
it("falls back to defaultEnglishTitle when the section type is unknown", () => {
|
||||
const translator = makeTranslator();
|
||||
const resolve = createSectionTitleResolver(translator);
|
||||
|
||||
const result = resolve({
|
||||
sectionId: "unknown-section",
|
||||
locale: "en-US",
|
||||
sectionKind: "builtin",
|
||||
defaultEnglishTitle: "Fallback Title",
|
||||
});
|
||||
|
||||
expect(result).toBe("Fallback Title");
|
||||
});
|
||||
|
||||
it("falls back to the sectionId when neither title nor known type", () => {
|
||||
const translator = makeTranslator();
|
||||
const resolve = createSectionTitleResolver(translator);
|
||||
|
||||
const result = resolve({
|
||||
sectionId: "mystery",
|
||||
locale: "en-US",
|
||||
sectionKind: "builtin",
|
||||
});
|
||||
|
||||
expect(result).toBe("mystery");
|
||||
});
|
||||
|
||||
it("falls back to defaultEnglishTitle when translator returns empty string", () => {
|
||||
const translator = {
|
||||
_: vi.fn(() => ""),
|
||||
};
|
||||
const resolve = createSectionTitleResolver(translator);
|
||||
|
||||
const result = resolve({
|
||||
sectionId: "skills",
|
||||
locale: "en-US",
|
||||
sectionKind: "builtin",
|
||||
defaultEnglishTitle: "Habilidades",
|
||||
});
|
||||
|
||||
expect(result).toBe("Habilidades");
|
||||
});
|
||||
|
||||
it("falls back to sectionId when translator returns empty and no default given", () => {
|
||||
const translator = { _: vi.fn(() => "") };
|
||||
const resolve = createSectionTitleResolver(translator);
|
||||
|
||||
const result = resolve({
|
||||
sectionId: "languages",
|
||||
locale: "en-US",
|
||||
sectionKind: "builtin",
|
||||
});
|
||||
|
||||
expect(result).toBe("languages");
|
||||
});
|
||||
|
||||
it("resolves all known built-in section ids without errors", () => {
|
||||
const translator = makeTranslator();
|
||||
const resolve = createSectionTitleResolver(translator);
|
||||
|
||||
const ids = [
|
||||
"summary",
|
||||
"profiles",
|
||||
"experience",
|
||||
"education",
|
||||
"projects",
|
||||
"skills",
|
||||
"languages",
|
||||
"interests",
|
||||
"awards",
|
||||
"certifications",
|
||||
"publications",
|
||||
"volunteer",
|
||||
"references",
|
||||
] as const;
|
||||
|
||||
for (const sectionId of ids) {
|
||||
const result = resolve({ sectionId, locale: "en-US", sectionKind: "builtin" });
|
||||
expect(typeof result).toBe("string");
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { isValidElement } from "react";
|
||||
import { getSectionIcon, getSectionTitle, leftSidebarSections, rightSidebarSections } from "./section";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const ALL_SECTIONS = [...leftSidebarSections, ...rightSidebarSections, "cover-letter"] as const;
|
||||
|
||||
describe("getSectionTitle", () => {
|
||||
it("returns a non-empty string for every known sidebar section", () => {
|
||||
for (const section of ALL_SECTIONS) {
|
||||
const title = getSectionTitle(section);
|
||||
expect(typeof title, section).toBe("string");
|
||||
expect(title.length, section).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("returns distinct titles for each section", () => {
|
||||
const titles = ALL_SECTIONS.map((section) => getSectionTitle(section));
|
||||
expect(new Set(titles).size).toBe(titles.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSectionIcon", () => {
|
||||
it("returns a React element for every known sidebar section", () => {
|
||||
for (const section of ALL_SECTIONS) {
|
||||
const icon = getSectionIcon(section);
|
||||
expect(isValidElement(icon), section).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("forwards icon props such as className", () => {
|
||||
const icon = getSectionIcon("skills", { className: "custom-class" });
|
||||
const props = (icon as React.ReactElement).props as { className?: string };
|
||||
expect(props.className).toContain("custom-class");
|
||||
// Always merges the shrink-0 baseline class.
|
||||
expect(props.className).toContain("shrink-0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sidebar section collections", () => {
|
||||
it("expose the documented left-sidebar set", () => {
|
||||
expect(leftSidebarSections).toContain("picture");
|
||||
expect(leftSidebarSections).toContain("basics");
|
||||
expect(leftSidebarSections).toContain("experience");
|
||||
expect(leftSidebarSections).toContain("custom");
|
||||
});
|
||||
|
||||
it("expose the documented right-sidebar set", () => {
|
||||
expect(rightSidebarSections).toContain("template");
|
||||
expect(rightSidebarSections).toContain("design");
|
||||
expect(rightSidebarSections).toContain("export");
|
||||
});
|
||||
|
||||
it("do not overlap (every section belongs to exactly one sidebar)", () => {
|
||||
const overlap = leftSidebarSections.filter((s) => (rightSidebarSections as readonly string[]).includes(s));
|
||||
expect(overlap).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
vi.stubGlobal("__APP_VERSION__", "9.9.9");
|
||||
|
||||
// The footer module evaluates `socialLinks = [{ label: t`...`, ... }]` at module
|
||||
// scope. That `t` call needs an activated locale BEFORE the import, so do that
|
||||
// here instead of in beforeAll.
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
|
||||
const { Footer } = await import("./footer");
|
||||
|
||||
const renderFooter = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Footer />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("Footer", () => {
|
||||
it("renders Resources and Community link group headings", () => {
|
||||
renderFooter();
|
||||
expect(screen.getByText("Resources")).toBeInTheDocument();
|
||||
expect(screen.getByText("Community")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the documented resource links", () => {
|
||||
const { container } = renderFooter();
|
||||
const text = container.textContent ?? "";
|
||||
for (const label of ["Documentation", "Sponsorships", "Source Code", "Changelog"]) {
|
||||
expect(text, label).toContain(label);
|
||||
}
|
||||
});
|
||||
|
||||
it("renders the documented community links", () => {
|
||||
const { container } = renderFooter();
|
||||
const text = container.textContent ?? "";
|
||||
for (const label of ["Report an issue", "Translations", "Subreddit", "Discord"]) {
|
||||
expect(text, label).toContain(label);
|
||||
}
|
||||
});
|
||||
|
||||
it("renders social media icon links to GitHub, LinkedIn, and X", () => {
|
||||
const { container } = renderFooter();
|
||||
const hrefs = Array.from(container.querySelectorAll<HTMLAnchorElement>("a")).map((a) => a.href);
|
||||
expect(hrefs.some((h) => h.includes("github.com/amruthpillai/reactive-resume"))).toBe(true);
|
||||
expect(hrefs.some((h) => h.includes("linkedin.com/in/amruthpillai"))).toBe(true);
|
||||
expect(hrefs.some((h) => h.includes("x.com/KingOKings"))).toBe(true);
|
||||
});
|
||||
|
||||
it("includes Reactive Resume version copy via Copyright", () => {
|
||||
renderFooter();
|
||||
expect(screen.getByText(/v9\.9\.9/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
vi.mock("@tanstack/react-router", () => ({
|
||||
Link: ({ children, to, ...rest }: React.PropsWithChildren<{ to: string }>) => (
|
||||
<a href={typeof to === "string" ? to : "#"} {...rest}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}));
|
||||
vi.mock("@/components/input/github-stars-button", () => ({
|
||||
GithubStarsButton: () => <div data-testid="github-stars-button" />,
|
||||
}));
|
||||
vi.mock("@/components/locale/combobox", () => ({
|
||||
LocaleCombobox: ({ render: renderProp }: { render: React.ReactElement }) => renderProp,
|
||||
}));
|
||||
vi.mock("@/components/theme/toggle-button", () => ({
|
||||
ThemeToggleButton: () => <button type="button" data-testid="theme-toggle" />,
|
||||
}));
|
||||
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
|
||||
const { Header } = await import("./header");
|
||||
|
||||
const renderHeader = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Header />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("Header", () => {
|
||||
it("renders a homepage link with the brand icon", () => {
|
||||
const { container } = renderHeader();
|
||||
const home = Array.from(container.querySelectorAll("a")).find((a) => a.getAttribute("href") === "/");
|
||||
expect(home).toBeDefined();
|
||||
expect(home?.getAttribute("aria-label")).toBe("Reactive Resume - Go to homepage");
|
||||
});
|
||||
|
||||
it("renders a dashboard link with the documented aria-label", () => {
|
||||
const { container } = renderHeader();
|
||||
const dashboard = Array.from(container.querySelectorAll("a")).find((a) => a.getAttribute("href") === "/dashboard");
|
||||
expect(dashboard).toBeDefined();
|
||||
});
|
||||
|
||||
it("includes ThemeToggleButton and GithubStarsButton in the navigation", () => {
|
||||
const { getByTestId } = renderHeader();
|
||||
expect(getByTestId("theme-toggle")).toBeInTheDocument();
|
||||
expect(getByTestId("github-stars-button")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("labels the navigation landmark", () => {
|
||||
const { container } = renderHeader();
|
||||
const nav = container.querySelector("nav") as HTMLElement;
|
||||
expect(nav.getAttribute("aria-label")).toBe("Main navigation");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { Prefooter } from "./prefooter";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderPrefooter = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<Prefooter />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("Prefooter", () => {
|
||||
it("renders the community tagline as a heading", () => {
|
||||
renderPrefooter();
|
||||
expect(screen.getByText("By the community, for the community.")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the community-thanks paragraph", () => {
|
||||
renderPrefooter();
|
||||
expect(screen.getByText(/vibrant community/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the decorative TextMaskEffect (svg)", () => {
|
||||
const { container } = renderPrefooter();
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { useBuilderAssistantStore } from "./assistant-store";
|
||||
|
||||
afterEach(() => useBuilderAssistantStore.setState({ isOpen: false }));
|
||||
|
||||
describe("useBuilderAssistantStore", () => {
|
||||
it("starts closed", () => {
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("setOpen overrides the open state directly", () => {
|
||||
useBuilderAssistantStore.getState().setOpen(true);
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(true);
|
||||
|
||||
useBuilderAssistantStore.getState().setOpen(false);
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(false);
|
||||
});
|
||||
|
||||
it("toggleOpen flips the state", () => {
|
||||
const { toggleOpen } = useBuilderAssistantStore.getState();
|
||||
|
||||
toggleOpen();
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(true);
|
||||
|
||||
toggleOpen();
|
||||
expect(useBuilderAssistantStore.getState().isOpen).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { BuilderSidebarEdge } from "./edge";
|
||||
|
||||
describe("BuilderSidebarEdge", () => {
|
||||
it("renders its children inside the edge container", () => {
|
||||
const { getByText } = render(
|
||||
<BuilderSidebarEdge side="left">
|
||||
<span>child</span>
|
||||
</BuilderSidebarEdge>,
|
||||
);
|
||||
expect(getByText("child")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses left-side classes (inset-s-0 + border-r) when side='left'", () => {
|
||||
const { container } = render(
|
||||
<BuilderSidebarEdge side="left">
|
||||
<span>x</span>
|
||||
</BuilderSidebarEdge>,
|
||||
);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("inset-s-0");
|
||||
expect(wrapper.className).toContain("border-r");
|
||||
});
|
||||
|
||||
it("uses right-side classes (inset-e-0 + border-l) when side='right'", () => {
|
||||
const { container } = render(
|
||||
<BuilderSidebarEdge side="right">
|
||||
<span>x</span>
|
||||
</BuilderSidebarEdge>,
|
||||
);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("inset-e-0");
|
||||
expect(wrapper.className).toContain("border-l");
|
||||
});
|
||||
|
||||
it("is hidden on mobile (hidden + sm:flex)", () => {
|
||||
const { container } = render(
|
||||
<BuilderSidebarEdge side="left">
|
||||
<span>x</span>
|
||||
</BuilderSidebarEdge>,
|
||||
);
|
||||
const wrapper = container.firstChild as HTMLElement;
|
||||
expect(wrapper.className).toContain("hidden");
|
||||
expect(wrapper.className).toContain("sm:flex");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_BUILDER_PREVIEW_PAGE_LAYOUT, getNextBuilderPreviewPageLayout } from "./page-layout";
|
||||
|
||||
describe("DEFAULT_BUILDER_PREVIEW_PAGE_LAYOUT", () => {
|
||||
it("defaults to horizontal", () => {
|
||||
expect(DEFAULT_BUILDER_PREVIEW_PAGE_LAYOUT).toBe("horizontal");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getNextBuilderPreviewPageLayout", () => {
|
||||
it("returns vertical when given horizontal", () => {
|
||||
expect(getNextBuilderPreviewPageLayout("horizontal")).toBe("vertical");
|
||||
});
|
||||
|
||||
it("returns horizontal when given vertical", () => {
|
||||
expect(getNextBuilderPreviewPageLayout("vertical")).toBe("horizontal");
|
||||
});
|
||||
|
||||
it("is its own inverse", () => {
|
||||
const start: "horizontal" | "vertical" = "horizontal";
|
||||
const back = getNextBuilderPreviewPageLayout(getNextBuilderPreviewPageLayout(start));
|
||||
expect(back).toBe(start);
|
||||
});
|
||||
});
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const educationItems = vi.hoisted(() => [
|
||||
{
|
||||
id: "e1",
|
||||
school: "MIT",
|
||||
degree: "BS",
|
||||
area: "CS",
|
||||
grade: "",
|
||||
location: "",
|
||||
period: "2010-2014",
|
||||
description: "",
|
||||
hidden: false,
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
]);
|
||||
const experienceItems = vi.hoisted(() => [
|
||||
// Experience with position set
|
||||
{
|
||||
id: "x1",
|
||||
company: "Acme",
|
||||
position: "Senior Engineer",
|
||||
location: "",
|
||||
period: "2020-2024",
|
||||
description: "",
|
||||
hidden: false,
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
roles: [],
|
||||
},
|
||||
// Experience with empty position and multiple roles → falls back to "N roles"
|
||||
{
|
||||
id: "x2",
|
||||
company: "BetaCo",
|
||||
position: "",
|
||||
location: "",
|
||||
period: "2015-2020",
|
||||
description: "",
|
||||
hidden: false,
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
roles: [
|
||||
{ position: "Engineer", period: "" },
|
||||
{ position: "Lead", period: "" },
|
||||
],
|
||||
},
|
||||
// Experience with empty position and one role → "1 role"
|
||||
{
|
||||
id: "x3",
|
||||
company: "Gamma",
|
||||
position: "",
|
||||
location: "",
|
||||
period: "2014",
|
||||
description: "",
|
||||
hidden: false,
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
roles: [{ position: "Intern", period: "" }],
|
||||
},
|
||||
]);
|
||||
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: {
|
||||
sections: {
|
||||
education: { title: "Education", columns: 1, hidden: false, items: educationItems },
|
||||
experience: { title: "Experience", columns: 1, hidden: false, items: experienceItems },
|
||||
},
|
||||
},
|
||||
}),
|
||||
useUpdateResumeData: () => vi.fn(),
|
||||
}));
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
vi.mock("../shared/section-item", () => ({
|
||||
SectionAddItemButton: ({ children }: { children: React.ReactNode }) => <button type="button">{children}</button>,
|
||||
SectionItem: ({ title, subtitle }: { title: string; subtitle: string }) => (
|
||||
<div>
|
||||
<span data-testid="item-title">{title}</span>
|
||||
<span data-testid="item-subtitle">{subtitle}</span>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const { EducationSectionBuilder } = await import("./education");
|
||||
const { ExperienceSectionBuilder } = await import("./experience");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const wrap = (ui: React.ReactNode) => <I18nProvider i18n={i18n}>{ui}</I18nProvider>;
|
||||
|
||||
describe("EducationSectionBuilder", () => {
|
||||
it("maps school → title and degree → subtitle", () => {
|
||||
render(wrap(<EducationSectionBuilder />));
|
||||
expect(screen.getByTestId("item-title").textContent).toBe("MIT");
|
||||
expect(screen.getByTestId("item-subtitle").textContent).toBe("BS");
|
||||
});
|
||||
|
||||
it("renders the Add a new education affordance", () => {
|
||||
render(wrap(<EducationSectionBuilder />));
|
||||
expect(screen.getByRole("button", { name: "Add a new education" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ExperienceSectionBuilder", () => {
|
||||
it("uses position as subtitle when present", () => {
|
||||
render(wrap(<ExperienceSectionBuilder />));
|
||||
const subtitles = screen.getAllByTestId("item-subtitle").map((el) => el.textContent);
|
||||
expect(subtitles[0]).toBe("Senior Engineer");
|
||||
});
|
||||
|
||||
it("falls back to 'N roles' when position is empty and multiple roles exist", () => {
|
||||
render(wrap(<ExperienceSectionBuilder />));
|
||||
const subtitles = screen.getAllByTestId("item-subtitle").map((el) => el.textContent);
|
||||
expect(subtitles[1]).toBe("2 roles");
|
||||
});
|
||||
|
||||
it("uses '1 role' (singular) for a single role entry", () => {
|
||||
render(wrap(<ExperienceSectionBuilder />));
|
||||
const subtitles = screen.getAllByTestId("item-subtitle").map((el) => el.textContent);
|
||||
expect(subtitles[2]).toBe("1 role");
|
||||
});
|
||||
|
||||
it("renders the Add a new experience affordance", () => {
|
||||
render(wrap(<ExperienceSectionBuilder />));
|
||||
expect(screen.getByRole("button", { name: "Add a new experience" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,188 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
//
|
||||
// Bulk-cover the small reorderable section components — they all share the same
|
||||
// shape: render a SectionItem per data row with title/subtitle mapped to specific
|
||||
// fields, plus an "Add a new X" button. Test them together to amortize the mock setup.
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const sections = vi.hoisted(() => ({
|
||||
awards: [
|
||||
{
|
||||
id: "a1",
|
||||
title: "Hackathon Winner",
|
||||
awarder: "Acme",
|
||||
date: "2024",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
],
|
||||
certifications: [
|
||||
{
|
||||
id: "c1",
|
||||
title: "AWS Solutions Architect",
|
||||
issuer: "AWS",
|
||||
date: "2024",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
],
|
||||
interests: [{ id: "i1", name: "Cooking", keywords: [], hidden: false, icon: "", iconColor: "" }],
|
||||
languages: [{ id: "l1", language: "English", fluency: "Native", level: 5, hidden: false }],
|
||||
publications: [
|
||||
{
|
||||
id: "p1",
|
||||
title: "On Type Systems",
|
||||
publisher: "ACM",
|
||||
date: "2024",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
],
|
||||
references: [
|
||||
{
|
||||
id: "r1",
|
||||
name: "Bob Smith",
|
||||
position: "Manager",
|
||||
phone: "",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
],
|
||||
volunteer: [
|
||||
{
|
||||
id: "v1",
|
||||
organization: "Code for Good",
|
||||
position: "Mentor",
|
||||
location: "Berlin",
|
||||
period: "2022",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
summary: "",
|
||||
},
|
||||
],
|
||||
}));
|
||||
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: {
|
||||
sections: {
|
||||
awards: { title: "Awards", columns: 1, hidden: false, items: sections.awards },
|
||||
certifications: { title: "Certifications", columns: 1, hidden: false, items: sections.certifications },
|
||||
interests: { title: "Interests", columns: 1, hidden: false, items: sections.interests },
|
||||
languages: { title: "Languages", columns: 1, hidden: false, items: sections.languages },
|
||||
publications: { title: "Publications", columns: 1, hidden: false, items: sections.publications },
|
||||
references: { title: "References", columns: 1, hidden: false, items: sections.references },
|
||||
volunteer: { title: "Volunteer", columns: 1, hidden: false, items: sections.volunteer },
|
||||
},
|
||||
},
|
||||
}),
|
||||
useUpdateResumeData: () => vi.fn(),
|
||||
}));
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children, className }: { children: React.ReactNode; className?: string }) => (
|
||||
<div className={className} data-testid="section-base">
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
vi.mock("../shared/section-item", () => ({
|
||||
SectionAddItemButton: ({ children }: { children: React.ReactNode }) => (
|
||||
<button type="button" data-testid="add-button">
|
||||
{children}
|
||||
</button>
|
||||
),
|
||||
SectionItem: ({ title, subtitle }: { title: string; subtitle: string }) => (
|
||||
<div>
|
||||
<span data-testid="item-title">{title}</span>
|
||||
<span data-testid="item-subtitle">{subtitle}</span>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const { AwardsSectionBuilder } = await import("./awards");
|
||||
const { CertificationsSectionBuilder } = await import("./certifications");
|
||||
const { InterestsSectionBuilder } = await import("./interests");
|
||||
const { LanguagesSectionBuilder } = await import("./languages");
|
||||
const { PublicationsSectionBuilder } = await import("./publications");
|
||||
const { ReferencesSectionBuilder } = await import("./references");
|
||||
const { VolunteerSectionBuilder } = await import("./volunteer");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const wrap = (ui: React.ReactNode) => <I18nProvider i18n={i18n}>{ui}</I18nProvider>;
|
||||
|
||||
describe("left sidebar section builders — title/subtitle mapping", () => {
|
||||
const cases = [
|
||||
{
|
||||
name: "awards",
|
||||
Component: AwardsSectionBuilder,
|
||||
title: "Hackathon Winner",
|
||||
subtitle: "Acme",
|
||||
addCopy: "Add a new award",
|
||||
},
|
||||
{
|
||||
name: "certifications",
|
||||
Component: CertificationsSectionBuilder,
|
||||
title: "AWS Solutions Architect",
|
||||
subtitle: "AWS • 2024",
|
||||
addCopy: "Add a new certification",
|
||||
},
|
||||
{
|
||||
name: "interests",
|
||||
Component: InterestsSectionBuilder,
|
||||
title: "Cooking",
|
||||
subtitle: "",
|
||||
addCopy: "Add a new interest",
|
||||
},
|
||||
{
|
||||
name: "languages",
|
||||
Component: LanguagesSectionBuilder,
|
||||
title: "English",
|
||||
subtitle: "Native",
|
||||
addCopy: "Add a new language",
|
||||
},
|
||||
{
|
||||
name: "publications",
|
||||
Component: PublicationsSectionBuilder,
|
||||
title: "On Type Systems",
|
||||
subtitle: "ACM",
|
||||
addCopy: "Add a new publication",
|
||||
},
|
||||
{
|
||||
name: "references",
|
||||
Component: ReferencesSectionBuilder,
|
||||
title: "Bob Smith",
|
||||
subtitle: "",
|
||||
addCopy: "Add a new reference",
|
||||
},
|
||||
{
|
||||
name: "volunteer",
|
||||
Component: VolunteerSectionBuilder,
|
||||
title: "Code for Good",
|
||||
subtitle: "Berlin",
|
||||
addCopy: "Add a new volunteer experience",
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const { name, Component, title, subtitle, addCopy } of cases) {
|
||||
it(`${name}: maps fields and renders the add button`, () => {
|
||||
const { unmount } = render(wrap(<Component />));
|
||||
expect(screen.getByTestId("item-title").textContent).toBe(title);
|
||||
expect(screen.getByTestId("item-subtitle").textContent ?? "").toBe(subtitle);
|
||||
expect(screen.getByRole("button", { name: addCopy })).toBeInTheDocument();
|
||||
unmount();
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const sectionItems = vi.hoisted(() => [
|
||||
{
|
||||
id: "p1",
|
||||
hidden: false,
|
||||
network: "GitHub",
|
||||
username: "jane",
|
||||
icon: "github",
|
||||
iconColor: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
{
|
||||
id: "p2",
|
||||
hidden: false,
|
||||
network: "LinkedIn",
|
||||
username: "jane-doe",
|
||||
icon: "linkedin",
|
||||
iconColor: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
]);
|
||||
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: {
|
||||
sections: { profiles: { title: "Profiles", columns: 1, hidden: false, items: sectionItems } },
|
||||
},
|
||||
}),
|
||||
useUpdateResumeData: () => vi.fn(),
|
||||
}));
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children, className }: { children: React.ReactNode; className?: string }) => (
|
||||
<div className={className} data-testid="section-base">
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
vi.mock("../shared/section-item", () => ({
|
||||
SectionAddItemButton: ({ children }: { children: React.ReactNode }) => <button type="button">{children}</button>,
|
||||
SectionItem: ({ title, subtitle }: { title: string; subtitle: string }) => (
|
||||
<div>
|
||||
<span data-testid="item-title">{title}</span>
|
||||
<span data-testid="item-subtitle">{subtitle}</span>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const { ProfilesSectionBuilder } = await import("./profiles");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("ProfilesSectionBuilder", () => {
|
||||
it("renders one SectionItem per profile with network as title and username as subtitle", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ProfilesSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
const titles = screen.getAllByTestId("item-title").map((el) => el.textContent);
|
||||
expect(titles).toEqual(["GitHub", "LinkedIn"]);
|
||||
|
||||
const subtitles = screen.getAllByTestId("item-subtitle").map((el) => el.textContent);
|
||||
expect(subtitles).toEqual(["jane", "jane-doe"]);
|
||||
});
|
||||
|
||||
it("renders the 'Add a new profile' affordance", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ProfilesSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Add a new profile" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("uses non-dashed border when items are present", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ProfilesSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
const wrapper = screen.getByTestId("section-base");
|
||||
expect(wrapper.className).toContain("border");
|
||||
expect(wrapper.className).not.toContain("border-dashed");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const items = vi.hoisted(() => [
|
||||
// Both period and website label present → "2024 • Site"
|
||||
{
|
||||
id: "p1",
|
||||
name: "Open CLI",
|
||||
period: "2024",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "https://example.com", label: "Site", inlineLink: false },
|
||||
},
|
||||
// Only period
|
||||
{
|
||||
id: "p2",
|
||||
name: "Plugin",
|
||||
period: "2023",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "", label: "", inlineLink: false },
|
||||
},
|
||||
// No period, no label
|
||||
{
|
||||
id: "p3",
|
||||
name: "Drafts",
|
||||
period: "",
|
||||
hidden: false,
|
||||
description: "",
|
||||
website: { url: "", label: " ", inlineLink: false },
|
||||
},
|
||||
]);
|
||||
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: { sections: { projects: { title: "Projects", columns: 1, hidden: false, items } } },
|
||||
}),
|
||||
useUpdateResumeData: () => vi.fn(),
|
||||
}));
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
vi.mock("../shared/section-item", () => ({
|
||||
SectionAddItemButton: ({ children }: { children: React.ReactNode }) => <button type="button">{children}</button>,
|
||||
SectionItem: ({ title, subtitle }: { title: string; subtitle?: string }) => (
|
||||
<div>
|
||||
<span data-testid="item-title">{title}</span>
|
||||
<span data-testid="item-subtitle">{subtitle ?? "<undefined>"}</span>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const { ProjectsSectionBuilder } = await import("./projects");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("ProjectsSectionBuilder buildSubtitle", () => {
|
||||
it("joins period and website label with ' • ' when both are present", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ProjectsSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
const subtitles = screen.getAllByTestId("item-subtitle").map((el) => el.textContent);
|
||||
expect(subtitles[0]).toBe("2024 • Site");
|
||||
});
|
||||
|
||||
it("uses just the period when no website label is set", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ProjectsSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
const subtitles = screen.getAllByTestId("item-subtitle").map((el) => el.textContent);
|
||||
expect(subtitles[1]).toBe("2023");
|
||||
});
|
||||
|
||||
it("returns undefined when neither period nor a non-blank website label is provided", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ProjectsSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
const subtitles = screen.getAllByTestId("item-subtitle").map((el) => el.textContent);
|
||||
// Mock stub renders the literal string "<undefined>" when subtitle was undefined.
|
||||
expect(subtitles[2]).toBe("<undefined>");
|
||||
});
|
||||
|
||||
it("renders the Add a new project affordance", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ProjectsSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Add a new project" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const sectionItems = vi.hoisted(() => [
|
||||
{ id: "s1", name: "TypeScript", proficiency: "Expert", level: 5, keywords: [], description: "", hidden: false },
|
||||
{ id: "s2", name: "Go", proficiency: "Intermediate", level: 3, keywords: [], description: "", hidden: false },
|
||||
]);
|
||||
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: { sections: { skills: { title: "Skills", columns: 1, hidden: false, items: sectionItems } } },
|
||||
}),
|
||||
useUpdateResumeData: () => vi.fn(),
|
||||
}));
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children, className }: { children: React.ReactNode; className?: string }) => (
|
||||
<div className={className} data-testid="section-base">
|
||||
{children}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
vi.mock("../shared/section-item", () => ({
|
||||
SectionAddItemButton: ({ children }: { children: React.ReactNode }) => <button type="button">{children}</button>,
|
||||
SectionItem: ({ title, subtitle }: { title: string; subtitle: string }) => (
|
||||
<div>
|
||||
<span data-testid="item-title">{title}</span>
|
||||
<span data-testid="item-subtitle">{subtitle}</span>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
const { SkillsSectionBuilder } = await import("./skills");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("SkillsSectionBuilder", () => {
|
||||
it("renders one SectionItem per skill, mapping name → title and proficiency → subtitle", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<SkillsSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getAllByTestId("item-title").map((el) => el.textContent)).toEqual(["TypeScript", "Go"]);
|
||||
expect(screen.getAllByTestId("item-subtitle").map((el) => el.textContent)).toEqual(["Expert", "Intermediate"]);
|
||||
});
|
||||
|
||||
it("renders an Add a new skill affordance", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<SkillsSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
expect(screen.getByRole("button", { name: "Add a new skill" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { defaultResumeData } from "@reactive-resume/schema/resume/default";
|
||||
|
||||
const downloadWithAnchor = vi.hoisted(() => vi.fn());
|
||||
const buildDocx = vi.hoisted(() => vi.fn().mockResolvedValue(new Blob(["x"], { type: "application/x-docx" })));
|
||||
const createResumePdfBlob = vi.hoisted(() => vi.fn().mockResolvedValue(new Blob(["x"], { type: "application/pdf" })));
|
||||
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
vi.mock("@reactive-resume/utils/file", () => ({
|
||||
downloadWithAnchor,
|
||||
generateFilename: (name: string, ext: string) => `${name}.${ext}`,
|
||||
}));
|
||||
vi.mock("@reactive-resume/utils/resume/docx", () => ({ buildDocx }));
|
||||
vi.mock("@/libs/resume/pdf-document", () => ({ createResumePdfBlob }));
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useResume: () => ({ id: "r1", name: "My Resume", data: defaultResumeData }),
|
||||
}));
|
||||
|
||||
const { ExportSectionBuilder } = await import("./export");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
downloadWithAnchor.mockReset();
|
||||
buildDocx.mockClear();
|
||||
createResumePdfBlob.mockClear();
|
||||
});
|
||||
|
||||
const renderExport = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<ExportSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("ExportSectionBuilder", () => {
|
||||
it("renders JSON, DOCX, and PDF action buttons", () => {
|
||||
renderExport();
|
||||
expect(screen.getByText("JSON")).toBeInTheDocument();
|
||||
expect(screen.getByText("DOCX")).toBeInTheDocument();
|
||||
expect(screen.getByText("PDF")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("downloads a JSON blob when the JSON button is clicked", () => {
|
||||
renderExport();
|
||||
const button = screen.getByText("JSON").closest("button") as HTMLButtonElement;
|
||||
fireEvent.click(button);
|
||||
|
||||
expect(downloadWithAnchor).toHaveBeenCalledTimes(1);
|
||||
// biome-ignore lint/style/noNonNullAssertion: The assertion above verifies the download call exists before destructuring it.
|
||||
const [blob, filename] = downloadWithAnchor.mock.calls[0]!;
|
||||
expect(blob).toBeInstanceOf(Blob);
|
||||
expect((blob as Blob).type).toBe("application/json");
|
||||
expect(filename).toBe("My Resume.json");
|
||||
});
|
||||
|
||||
it("calls buildDocx and downloads the resulting blob when DOCX is clicked", async () => {
|
||||
renderExport();
|
||||
const button = screen.getByText("DOCX").closest("button") as HTMLButtonElement;
|
||||
|
||||
fireEvent.click(button);
|
||||
// Wait for the async callback chain to settle.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(buildDocx).toHaveBeenCalledTimes(1);
|
||||
expect(downloadWithAnchor).toHaveBeenCalledTimes(1);
|
||||
expect(downloadWithAnchor.mock.calls[0]?.[1]).toBe("My Resume.docx");
|
||||
});
|
||||
|
||||
it("calls createResumePdfBlob and downloads when PDF is clicked", async () => {
|
||||
renderExport();
|
||||
const button = screen.getByText("PDF").closest("button") as HTMLButtonElement;
|
||||
|
||||
fireEvent.click(button);
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(createResumePdfBlob).toHaveBeenCalledTimes(1);
|
||||
expect(downloadWithAnchor).toHaveBeenCalledTimes(1);
|
||||
expect(downloadWithAnchor.mock.calls[0]?.[1]).toBe("My Resume.pdf");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
|
||||
const { InformationSectionBuilder } = await import("./information");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
const renderInfo = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<InformationSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("InformationSectionBuilder", () => {
|
||||
it("renders the donation prompt and CTA", () => {
|
||||
renderInfo();
|
||||
expect(screen.getByText("Support the app by doing what you can!")).toBeInTheDocument();
|
||||
expect(screen.getByText("Donate to Reactive Resume")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("links to the OpenCollective donation page", () => {
|
||||
renderInfo();
|
||||
const donateLink = screen.getByText("Donate to Reactive Resume").closest("a");
|
||||
expect(donateLink?.getAttribute("href")).toBe("http://opencollective.com/reactive-resume");
|
||||
});
|
||||
|
||||
it("includes external resource links (docs, source, bugs, translations, sponsors)", () => {
|
||||
renderInfo();
|
||||
const labels = ["Documentation", "Source Code", "Report a Bug", "Translations", "Sponsors"];
|
||||
for (const label of labels) {
|
||||
expect(screen.getByText(label).closest("a"), label).not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens external links in a new tab", () => {
|
||||
renderInfo();
|
||||
const docs = screen.getByText("Documentation").closest("a") as HTMLAnchorElement;
|
||||
expect(docs.getAttribute("target")).toBe("_blank");
|
||||
expect(docs.getAttribute("rel")).toBe("noopener");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const updateResumeData = vi.hoisted(() => vi.fn());
|
||||
const richInputProps = vi.hoisted(() => ({
|
||||
value: undefined as string | undefined,
|
||||
onChange: undefined as ((value: string) => void) | undefined,
|
||||
}));
|
||||
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children }: { children: React.ReactNode }) => <div data-testid="section-base">{children}</div>,
|
||||
}));
|
||||
vi.mock("@/components/input/rich-input", () => ({
|
||||
RichInput: (props: { value: string; onChange: (value: string) => void }) => {
|
||||
richInputProps.value = props.value;
|
||||
richInputProps.onChange = props.onChange;
|
||||
return <textarea data-testid="rich-input" value={props.value} readOnly />;
|
||||
},
|
||||
}));
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: { metadata: { notes: "saved notes" } },
|
||||
}),
|
||||
useUpdateResumeData: () => updateResumeData,
|
||||
}));
|
||||
|
||||
const { NotesSectionBuilder } = await import("./notes");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
describe("NotesSectionBuilder", () => {
|
||||
it("renders the privacy hint copy", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<NotesSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(/personal notes specific to this resume/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("seeds the rich input with the current notes value", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<NotesSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
expect(richInputProps.value).toBe("saved notes");
|
||||
});
|
||||
|
||||
it("forwards rich input changes through updateResumeData", () => {
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<NotesSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
richInputProps.onChange?.("<p>new note</p>");
|
||||
|
||||
expect(updateResumeData).toHaveBeenCalledTimes(1);
|
||||
|
||||
// updateResumeData receives a recipe that mutates the draft.
|
||||
const recipe = updateResumeData.mock.calls[0]?.[0] as (draft: { metadata: { notes: string } }) => void;
|
||||
const draft = { metadata: { notes: "" } };
|
||||
recipe(draft);
|
||||
expect(draft.metadata.notes).toBe("<p>new note</p>");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
|
||||
const queryResult = vi.hoisted(() => ({
|
||||
data: undefined as
|
||||
| undefined
|
||||
| {
|
||||
isPublic: boolean;
|
||||
views: number;
|
||||
downloads: number;
|
||||
lastViewedAt: Date | null;
|
||||
lastDownloadedAt: Date | null;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@tanstack/react-query", () => ({
|
||||
useQuery: () => queryResult,
|
||||
}));
|
||||
vi.mock("@tanstack/react-router", () => ({
|
||||
useParams: () => ({ resumeId: "r1" }),
|
||||
}));
|
||||
vi.mock("@/libs/orpc/client", () => ({
|
||||
orpc: { resume: { statistics: { getById: { queryOptions: () => ({}) } } } },
|
||||
}));
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
|
||||
const { StatisticsSectionBuilder } = await import("./statistics");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
queryResult.data = undefined;
|
||||
});
|
||||
|
||||
const renderStats = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<StatisticsSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("StatisticsSectionBuilder", () => {
|
||||
it("renders nothing while the query result is undefined", () => {
|
||||
const { container } = renderStats();
|
||||
expect(container.textContent).toBe("");
|
||||
});
|
||||
|
||||
it("renders the private hint when isPublic=false", () => {
|
||||
queryResult.data = {
|
||||
isPublic: false,
|
||||
views: 0,
|
||||
downloads: 0,
|
||||
lastViewedAt: null,
|
||||
lastDownloadedAt: null,
|
||||
};
|
||||
renderStats();
|
||||
expect(screen.getByText("Track your resume's views and downloads")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the views/downloads counters when isPublic=true", () => {
|
||||
queryResult.data = {
|
||||
isPublic: true,
|
||||
views: 42,
|
||||
downloads: 7,
|
||||
lastViewedAt: null,
|
||||
lastDownloadedAt: null,
|
||||
};
|
||||
renderStats();
|
||||
expect(screen.getByText("42")).toBeInTheDocument();
|
||||
expect(screen.getByText("7")).toBeInTheDocument();
|
||||
expect(screen.getByText("Views")).toBeInTheDocument();
|
||||
expect(screen.getByText("Downloads")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders 'last viewed/downloaded' timestamps when present", () => {
|
||||
queryResult.data = {
|
||||
isPublic: true,
|
||||
views: 1,
|
||||
downloads: 0,
|
||||
lastViewedAt: new Date("2024-01-15T00:00:00Z"),
|
||||
lastDownloadedAt: null,
|
||||
};
|
||||
renderStats();
|
||||
// Just verify some 'Last viewed' copy appears — the date formatting depends on the runner's locale.
|
||||
expect(screen.getByText(/Last viewed/i)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { I18nProvider } from "@lingui/react";
|
||||
import { useDialogStore } from "@/dialogs/store";
|
||||
|
||||
vi.mock("../shared/section-base", () => ({
|
||||
SectionBase: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
|
||||
}));
|
||||
vi.mock("@/components/resume/builder-resume-draft", () => ({
|
||||
useCurrentResume: () => ({
|
||||
data: { metadata: { template: "ditto" } },
|
||||
}),
|
||||
}));
|
||||
|
||||
const { TemplateSectionBuilder } = await import("./template");
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useDialogStore.setState({ open: false, activeDialog: null, onBeforeClose: null });
|
||||
});
|
||||
|
||||
const renderTemplate = () =>
|
||||
render(
|
||||
<I18nProvider i18n={i18n}>
|
||||
<TemplateSectionBuilder />
|
||||
</I18nProvider>,
|
||||
);
|
||||
|
||||
describe("TemplateSectionBuilder", () => {
|
||||
it("renders the current template's display name", () => {
|
||||
renderTemplate();
|
||||
expect(screen.getByRole("heading", { level: 3 }).textContent).toBe("Ditto");
|
||||
});
|
||||
|
||||
it("renders the template tags as badges", () => {
|
||||
renderTemplate();
|
||||
// Ditto's tags include 'ATS friendly' per templates/data.
|
||||
expect(screen.getByText("ATS friendly")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the template gallery dialog when the preview is clicked", () => {
|
||||
renderTemplate();
|
||||
|
||||
const preview = screen.getByAltText("Ditto").closest("button") as HTMLButtonElement;
|
||||
fireEvent.click(preview);
|
||||
|
||||
const state = useDialogStore.getState();
|
||||
expect(state.open).toBe(true);
|
||||
expect(state.activeDialog?.type).toBe("resume.template.gallery");
|
||||
});
|
||||
|
||||
it("renders the template preview image with the data-mapped URL", () => {
|
||||
renderTemplate();
|
||||
const img = screen.getByAltText("Ditto") as HTMLImageElement;
|
||||
expect(img.src).toContain("/templates/jpg/ditto.jpg");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { useSectionStore } from "./section";
|
||||
|
||||
afterEach(() => {
|
||||
useSectionStore.setState({ sections: {} });
|
||||
});
|
||||
|
||||
describe("useSectionStore", () => {
|
||||
it("starts with no collapsed sections", () => {
|
||||
expect(useSectionStore.getState().sections).toEqual({});
|
||||
});
|
||||
|
||||
it("setCollapsed stores collapse state for a single id", () => {
|
||||
useSectionStore.getState().setCollapsed("experience", true);
|
||||
|
||||
expect(useSectionStore.getState().sections.experience).toEqual({ collapsed: true });
|
||||
});
|
||||
|
||||
it("setCollapsed(false) overrides previous collapsed=true", () => {
|
||||
const { setCollapsed } = useSectionStore.getState();
|
||||
setCollapsed("skills", true);
|
||||
setCollapsed("skills", false);
|
||||
|
||||
expect(useSectionStore.getState().sections.skills).toEqual({ collapsed: false });
|
||||
});
|
||||
|
||||
it("toggleCollapsed flips from undefined → true → false", () => {
|
||||
const { toggleCollapsed } = useSectionStore.getState();
|
||||
|
||||
toggleCollapsed("education");
|
||||
expect(useSectionStore.getState().sections.education?.collapsed).toBe(true);
|
||||
|
||||
toggleCollapsed("education");
|
||||
expect(useSectionStore.getState().sections.education?.collapsed).toBe(false);
|
||||
});
|
||||
|
||||
it("toggleAll collapses all built-in sidebar sections from a clean state", () => {
|
||||
useSectionStore.getState().toggleAll();
|
||||
|
||||
const sections = useSectionStore.getState().sections;
|
||||
// Spot-check a few known sidebar section ids.
|
||||
expect(sections.experience?.collapsed).toBe(true);
|
||||
expect(sections.template?.collapsed).toBe(true);
|
||||
expect(sections.layout?.collapsed).toBe(true);
|
||||
expect(Object.keys(sections).length).toBeGreaterThan(10);
|
||||
});
|
||||
|
||||
it("toggleAll flips each individual section independently of the others", () => {
|
||||
const { setCollapsed, toggleAll } = useSectionStore.getState();
|
||||
|
||||
setCollapsed("skills", true); // skills starts collapsed=true
|
||||
// Other ids remain undefined → treated as collapsed=false by toggleCollapsed semantics.
|
||||
|
||||
toggleAll();
|
||||
|
||||
const sections = useSectionStore.getState().sections;
|
||||
expect(sections.skills?.collapsed).toBe(false);
|
||||
expect(sections.experience?.collapsed).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_BUILDER_LAYOUT,
|
||||
mapPanelLayoutToBuilderLayout,
|
||||
parseBuilderLayoutCookie,
|
||||
useBuilderSidebarStore,
|
||||
} from "./sidebar";
|
||||
|
||||
afterEach(() => {
|
||||
useBuilderSidebarStore.setState({
|
||||
layout: DEFAULT_BUILDER_LAYOUT,
|
||||
leftSidebar: null,
|
||||
rightSidebar: null,
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseBuilderLayoutCookie", () => {
|
||||
it("returns the default layout when value is undefined", () => {
|
||||
expect(parseBuilderLayoutCookie(undefined)).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the default layout when value is null", () => {
|
||||
expect(parseBuilderLayoutCookie(null)).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the default layout when value is an empty string", () => {
|
||||
expect(parseBuilderLayoutCookie("")).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the default layout when value is malformed JSON", () => {
|
||||
expect(parseBuilderLayoutCookie("{not-json")).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the default layout when value is a JSON array", () => {
|
||||
expect(parseBuilderLayoutCookie("[1,2,3]")).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the default layout when value is a JSON primitive", () => {
|
||||
expect(parseBuilderLayoutCookie("42")).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
expect(parseBuilderLayoutCookie("null")).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
expect(parseBuilderLayoutCookie('"string"')).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the default layout when any field is missing or not a number", () => {
|
||||
expect(parseBuilderLayoutCookie('{"left":10,"artboard":50}')).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
expect(parseBuilderLayoutCookie('{"left":"10","artboard":50,"right":40}')).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the parsed layout when all fields are numeric", () => {
|
||||
const json = JSON.stringify({ left: 10, artboard: 60, right: 30 });
|
||||
expect(parseBuilderLayoutCookie(json)).toEqual({ left: 10, artboard: 60, right: 30 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("mapPanelLayoutToBuilderLayout", () => {
|
||||
it("returns the default layout if any panel size is missing", () => {
|
||||
expect(mapPanelLayoutToBuilderLayout({} as never)).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
expect(mapPanelLayoutToBuilderLayout({ left: 10, artboard: 60 } as never)).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
});
|
||||
|
||||
it("returns the layout when all panel sizes are numeric", () => {
|
||||
const layout = mapPanelLayoutToBuilderLayout({ left: 15, artboard: 70, right: 15 } as never);
|
||||
expect(layout).toEqual({ left: 15, artboard: 70, right: 15 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("useBuilderSidebarStore", () => {
|
||||
it("starts with default layout and null panel refs", () => {
|
||||
const state = useBuilderSidebarStore.getState();
|
||||
expect(state.layout).toEqual(DEFAULT_BUILDER_LAYOUT);
|
||||
expect(state.leftSidebar).toBeNull();
|
||||
expect(state.rightSidebar).toBeNull();
|
||||
});
|
||||
|
||||
it("setLayout replaces the layout", () => {
|
||||
useBuilderSidebarStore.getState().setLayout({ left: 1, artboard: 98, right: 1 });
|
||||
expect(useBuilderSidebarStore.getState().layout).toEqual({ left: 1, artboard: 98, right: 1 });
|
||||
});
|
||||
|
||||
it("setLeftSidebar and setRightSidebar store refs", () => {
|
||||
const left = { foo: "left" } as never;
|
||||
const right = { foo: "right" } as never;
|
||||
|
||||
useBuilderSidebarStore.getState().setLeftSidebar(left);
|
||||
useBuilderSidebarStore.getState().setRightSidebar(right);
|
||||
|
||||
expect(useBuilderSidebarStore.getState().leftSidebar).toBe(left);
|
||||
expect(useBuilderSidebarStore.getState().rightSidebar).toBe(right);
|
||||
});
|
||||
|
||||
it("accepts null to clear sidebar refs", () => {
|
||||
useBuilderSidebarStore.getState().setLeftSidebar({ foo: "x" } as never);
|
||||
useBuilderSidebarStore.getState().setLeftSidebar(null);
|
||||
expect(useBuilderSidebarStore.getState().leftSidebar).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ListIcon } from "@phosphor-icons/react";
|
||||
import { SidebarProvider } from "@reactive-resume/ui/components/sidebar";
|
||||
import { DashboardHeader } from "./header";
|
||||
|
||||
const renderHeader = (props: Partial<React.ComponentProps<typeof DashboardHeader>> = {}) =>
|
||||
render(
|
||||
<SidebarProvider>
|
||||
<DashboardHeader title="Resumes" icon={ListIcon} {...props} />
|
||||
</SidebarProvider>,
|
||||
);
|
||||
|
||||
describe("DashboardHeader", () => {
|
||||
it("renders the title as an h1", () => {
|
||||
renderHeader();
|
||||
const heading = screen.getByRole("heading", { level: 1 });
|
||||
expect(heading.textContent).toBe("Resumes");
|
||||
});
|
||||
|
||||
it("renders the supplied icon as an SVG", () => {
|
||||
const { container } = renderHeader();
|
||||
expect(container.querySelector("svg")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("merges custom className into the wrapper", () => {
|
||||
const { container } = renderHeader({ className: "custom-class" });
|
||||
const wrapper = container.querySelector(".custom-class");
|
||||
expect(wrapper).not.toBeNull();
|
||||
});
|
||||
|
||||
it("includes the mobile sidebar trigger (hidden on md+)", () => {
|
||||
const { container } = renderHeader();
|
||||
const trigger = container.querySelector('[data-sidebar="trigger"]');
|
||||
expect(trigger).not.toBeNull();
|
||||
expect(trigger?.className).toContain("md:hidden");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { useDialogStore } from "@/dialogs/store";
|
||||
import { CreateResumeCard } from "./create-card";
|
||||
import { ImportResumeCard } from "./import-card";
|
||||
|
||||
beforeAll(() => {
|
||||
i18n.loadAndActivate({ locale: "en", messages: {} });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useDialogStore.setState({ open: false, activeDialog: null, onBeforeClose: null });
|
||||
});
|
||||
|
||||
describe("CreateResumeCard", () => {
|
||||
it("renders the create-resume copy", () => {
|
||||
render(<CreateResumeCard />);
|
||||
expect(screen.getByText("Create a new resume")).toBeInTheDocument();
|
||||
expect(screen.getByText("Start building your resume from scratch")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the resume.create dialog when clicked", () => {
|
||||
render(<CreateResumeCard />);
|
||||
|
||||
const card = screen.getByText("Create a new resume").closest("div[class*='aspect-page']") as HTMLElement;
|
||||
fireEvent.click(card);
|
||||
|
||||
const state = useDialogStore.getState();
|
||||
expect(state.open).toBe(true);
|
||||
expect(state.activeDialog?.type).toBe("resume.create");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ImportResumeCard", () => {
|
||||
it("renders the import-resume copy", () => {
|
||||
render(<ImportResumeCard />);
|
||||
expect(screen.getByText("Import an existing resume")).toBeInTheDocument();
|
||||
expect(screen.getByText("Continue where you left off")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("opens the resume.import dialog when clicked", () => {
|
||||
render(<ImportResumeCard />);
|
||||
|
||||
const card = screen.getByText("Import an existing resume").closest("div[class*='aspect-page']") as HTMLElement;
|
||||
fireEvent.click(card);
|
||||
|
||||
const state = useDialogStore.getState();
|
||||
expect(state.open).toBe(true);
|
||||
expect(state.activeDialog?.type).toBe("resume.import");
|
||||
});
|
||||
});
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getResumeThumbnailCacheKey,
|
||||
getResumeThumbnailRenderSize,
|
||||
RESUME_THUMBNAIL_TARGET_WIDTH,
|
||||
} from "./resume-thumbnail.shared";
|
||||
|
||||
describe("getResumeThumbnailCacheKey", () => {
|
||||
it("composes id and updated-at epoch milliseconds with a colon", () => {
|
||||
const date = new Date("2024-01-15T00:00:00.000Z");
|
||||
expect(getResumeThumbnailCacheKey("abc", date)).toBe(`abc:${date.getTime()}`);
|
||||
});
|
||||
|
||||
it("differs when updatedAt changes", () => {
|
||||
const id = "resume-1";
|
||||
const a = getResumeThumbnailCacheKey(id, new Date(1000));
|
||||
const b = getResumeThumbnailCacheKey(id, new Date(2000));
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getResumeThumbnailRenderSize", () => {
|
||||
it("uses the default target width when not provided", () => {
|
||||
const size = getResumeThumbnailRenderSize({ width: 800, height: 1200 });
|
||||
|
||||
expect(size.width).toBe(RESUME_THUMBNAIL_TARGET_WIDTH);
|
||||
// Scale = 420/800 = 0.525 → height rounds to 630
|
||||
expect(size.height).toBe(630);
|
||||
expect(size.scale).toBeCloseTo(0.525, 5);
|
||||
});
|
||||
|
||||
it("scales relative to the provided target width", () => {
|
||||
const size = getResumeThumbnailRenderSize({ width: 800, height: 1200 }, 400);
|
||||
expect(size.width).toBe(400);
|
||||
expect(size.scale).toBeCloseTo(0.5, 5);
|
||||
expect(size.height).toBe(600);
|
||||
});
|
||||
|
||||
it("clamps pixelRatio to a minimum of 1", () => {
|
||||
const a = getResumeThumbnailRenderSize({ width: 800, height: 1200 }, 400, 0.5);
|
||||
const b = getResumeThumbnailRenderSize({ width: 800, height: 1200 }, 400, 1);
|
||||
expect(a).toEqual(b);
|
||||
});
|
||||
|
||||
it("clamps pixelRatio to a maximum of 2", () => {
|
||||
const a = getResumeThumbnailRenderSize({ width: 800, height: 1200 }, 400, 3);
|
||||
const b = getResumeThumbnailRenderSize({ width: 800, height: 1200 }, 400, 2);
|
||||
expect(a).toEqual(b);
|
||||
});
|
||||
|
||||
it("multiplies width/height by pixelRatio when within bounds", () => {
|
||||
const size = getResumeThumbnailRenderSize({ width: 800, height: 1200 }, 400, 2);
|
||||
// pageScale = 0.5, outputScale = 2 → width = 800, height = 1200
|
||||
expect(size.width).toBe(800);
|
||||
expect(size.height).toBe(1200);
|
||||
expect(size.scale).toBeCloseTo(1, 5);
|
||||
});
|
||||
|
||||
it("rounds the output dimensions to integers", () => {
|
||||
const size = getResumeThumbnailRenderSize({ width: 793, height: 1123 }, 421, 1.5);
|
||||
expect(Number.isInteger(size.width)).toBe(true);
|
||||
expect(Number.isInteger(size.height)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildMcpServerCard } from "./mcp-server-card";
|
||||
import { MCP_TOOL_NAME } from "./mcp-tool-names";
|
||||
|
||||
describe("buildMcpServerCard", () => {
|
||||
const card = buildMcpServerCard("1.2.3");
|
||||
|
||||
it("includes the provided app version in serverInfo", () => {
|
||||
expect(card.serverInfo.version).toBe("1.2.3");
|
||||
});
|
||||
|
||||
it("identifies the server as reactive-resume", () => {
|
||||
expect(card.serverInfo.name).toBe("reactive-resume");
|
||||
expect(card.serverInfo.title).toBe("Reactive Resume");
|
||||
expect(card.serverInfo.websiteUrl).toBe("https://rxresu.me");
|
||||
});
|
||||
|
||||
it("exposes light + dark theme icons", () => {
|
||||
const themes = card.serverInfo.icons.map((icon) => icon.theme).sort();
|
||||
expect(themes).toEqual(["dark", "light"]);
|
||||
});
|
||||
|
||||
it("requires authentication with oauth2 + bearer schemes", () => {
|
||||
expect(card.authentication.required).toBe(true);
|
||||
expect(card.authentication.schemes).toContain("oauth2");
|
||||
expect(card.authentication.schemes).toContain("bearer");
|
||||
});
|
||||
|
||||
it("registers one entry per MCP tool", () => {
|
||||
const cardToolNames = card.tools.map((tool) => tool.name).sort();
|
||||
const expectedNames = Object.values(MCP_TOOL_NAME).sort();
|
||||
expect(cardToolNames).toEqual(expectedNames);
|
||||
});
|
||||
|
||||
it("declares a JSON Schema input for every tool", () => {
|
||||
for (const tool of card.tools) {
|
||||
expect(tool.inputSchema, tool.name).toBeDefined();
|
||||
expect(tool.annotations, tool.name).toBeDefined();
|
||||
expect(tool.title.length, tool.name).toBeGreaterThan(0);
|
||||
expect(tool.description.length, tool.name).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("registers the three documented prompts", () => {
|
||||
const promptNames = card.prompts.map((p) => p.name).sort();
|
||||
expect(promptNames).toEqual(["build_resume", "improve_resume", "review_resume"]);
|
||||
});
|
||||
|
||||
it("publishes a resource template for resume://{id}", () => {
|
||||
const template = card.resourceTemplates.find((r) => r.name === "resume");
|
||||
expect(template?.uriTemplate).toBe("resume://{id}");
|
||||
expect(template?.mimeType).toBe("application/json");
|
||||
});
|
||||
|
||||
it("includes resume and meta-schema in the static resources list", () => {
|
||||
const resourceNames = card.resources.map((r) => r.name);
|
||||
expect(resourceNames).toContain("resume");
|
||||
expect(card.resources.some((r) => r.mimeType === "application/json")).toBe(true);
|
||||
});
|
||||
|
||||
it("documents an optional apiKey in the configuration schema", () => {
|
||||
const props = card.configurationSchema.properties as Record<string, unknown>;
|
||||
expect(props.apiKey).toBeDefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
// biome-ignore-all lint/style/noNonNullAssertion: These tests assert registered prompt names before exercising their handlers.
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// `./tools` pulls in the env / db client modules which require runtime env vars.
|
||||
// `prompts.ts` only imports `MCP_TOOL_NAME` from `./tools`, so we stub it with the
|
||||
// pure constants module to keep this test isolated.
|
||||
vi.mock("./tools", async () => await import("./mcp-tool-names"));
|
||||
|
||||
const { registerPrompts } = await import("./prompts");
|
||||
|
||||
type Registration = {
|
||||
name: string;
|
||||
config: {
|
||||
title: string;
|
||||
description: string;
|
||||
argsSchema: Record<string, unknown>;
|
||||
};
|
||||
handler: (args: { id: string }) => Promise<{
|
||||
messages: Array<{
|
||||
role: "user";
|
||||
content: { type: string; text?: string; resource?: { uri: string; mimeType: string } };
|
||||
}>;
|
||||
}>;
|
||||
};
|
||||
|
||||
const makeFakeServer = () => {
|
||||
const registered: Registration[] = [];
|
||||
const server = {
|
||||
registerPrompt: vi.fn((name: string, config: Registration["config"], handler: Registration["handler"]) => {
|
||||
registered.push({ name, config, handler });
|
||||
}),
|
||||
};
|
||||
return { server, registered };
|
||||
};
|
||||
|
||||
describe("registerPrompts", () => {
|
||||
it("registers build_resume, improve_resume, and review_resume", () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
|
||||
registerPrompts(server as never);
|
||||
|
||||
expect(server.registerPrompt).toHaveBeenCalledTimes(3);
|
||||
expect(registered.map((r) => r.name).sort()).toEqual(["build_resume", "improve_resume", "review_resume"]);
|
||||
});
|
||||
|
||||
it("requires an `id` argument on every prompt", () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
|
||||
registerPrompts(server as never);
|
||||
|
||||
for (const reg of registered) {
|
||||
expect(reg.config.argsSchema.id, reg.name).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("build_resume handler attaches the resume + schema resources and a guidance text", async () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerPrompts(server as never);
|
||||
|
||||
const build = registered.find((r) => r.name === "build_resume")!;
|
||||
const result = await build.handler({ id: "abc-123" });
|
||||
|
||||
const resourceUris = result.messages
|
||||
.filter((m) => m.content.type === "resource")
|
||||
.map((m) => m.content.resource?.uri);
|
||||
|
||||
expect(resourceUris).toContain("resume://abc-123");
|
||||
expect(resourceUris).toContain("resume://_meta/schema");
|
||||
|
||||
const textMessage = result.messages.find((m) => m.content.type === "text");
|
||||
expect(textMessage?.content.text).toContain("step by step");
|
||||
expect(textMessage?.content.text).toContain("JSON Patch");
|
||||
});
|
||||
|
||||
it("improve_resume handler tells the model not to fabricate information", async () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerPrompts(server as never);
|
||||
|
||||
const improve = registered.find((r) => r.name === "improve_resume")!;
|
||||
const result = await improve.handler({ id: "id-1" });
|
||||
|
||||
const text = result.messages.find((m) => m.content.type === "text")?.content.text ?? "";
|
||||
expect(text).toContain("Do NOT fabricate");
|
||||
expect(text).toContain("Passive voice");
|
||||
});
|
||||
|
||||
it("review_resume handler is read-only and forbids patching", async () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerPrompts(server as never);
|
||||
|
||||
const review = registered.find((r) => r.name === "review_resume")!;
|
||||
const result = await review.handler({ id: "id-2" });
|
||||
|
||||
const text = result.messages.find((m) => m.content.type === "text")?.content.text ?? "";
|
||||
expect(text).toContain("read-only");
|
||||
expect(text).toContain("Do NOT call");
|
||||
expect(text).toContain("Scorecard");
|
||||
});
|
||||
|
||||
it("interpolates the provided resume id into the resource URI", async () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerPrompts(server as never);
|
||||
|
||||
const review = registered.find((r) => r.name === "review_resume")!;
|
||||
const result = await review.handler({ id: "8f-test" });
|
||||
|
||||
const resourceUris = result.messages
|
||||
.filter((m) => m.content.type === "resource")
|
||||
.map((m) => m.content.resource?.uri);
|
||||
|
||||
expect(resourceUris).toContain("resume://8f-test");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
// biome-ignore-all lint/style/noNonNullAssertion: These tests assert registered resource names before exercising their handlers.
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Avoid pulling in env-validated modules through `./tools`.
|
||||
vi.mock("./tools", async () => await import("./mcp-tool-names"));
|
||||
|
||||
const clientMock = vi.hoisted(() => ({
|
||||
resume: {
|
||||
getById: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/libs/orpc/client", () => ({ client: clientMock }));
|
||||
|
||||
const { registerResources } = await import("./resources");
|
||||
|
||||
type ResourceHandler = (uri: URL) => Promise<{
|
||||
contents: Array<{ uri: string; mimeType: string; text: string }>;
|
||||
}>;
|
||||
|
||||
type Registration = {
|
||||
name: string;
|
||||
uriOrTemplate: unknown;
|
||||
metadata: Record<string, unknown>;
|
||||
handler: ResourceHandler;
|
||||
};
|
||||
|
||||
const makeFakeServer = () => {
|
||||
const registered: Registration[] = [];
|
||||
const server = {
|
||||
registerResource: vi.fn(
|
||||
(name: string, uriOrTemplate: unknown, metadata: Record<string, unknown>, handler: ResourceHandler) => {
|
||||
registered.push({ name, uriOrTemplate, metadata, handler });
|
||||
},
|
||||
),
|
||||
};
|
||||
return { server, registered };
|
||||
};
|
||||
|
||||
describe("registerResources", () => {
|
||||
it("registers the resume and resume-schema resources", () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerResources(server as never);
|
||||
|
||||
expect(server.registerResource).toHaveBeenCalledTimes(2);
|
||||
expect(registered.map((r) => r.name).sort()).toEqual(["resume", "resume-schema"]);
|
||||
});
|
||||
|
||||
it("resume handler fetches resume data via the oRPC client and returns it as JSON", async () => {
|
||||
clientMock.resume.getById.mockResolvedValueOnce({ data: { id: "abc", basics: { name: "Jane" } } });
|
||||
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerResources(server as never);
|
||||
|
||||
const resume = registered.find((r) => r.name === "resume")!;
|
||||
const result = await resume.handler(new URL("resume://abc"));
|
||||
|
||||
expect(clientMock.resume.getById).toHaveBeenCalledWith({ id: "abc" });
|
||||
expect(result.contents[0]?.uri).toBe("resume://abc");
|
||||
expect(result.contents[0]?.mimeType).toBe("application/json");
|
||||
expect(JSON.parse(result.contents[0]?.text)).toEqual({ id: "abc", basics: { name: "Jane" } });
|
||||
});
|
||||
|
||||
it("resume handler throws when the URI has no id segment", async () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerResources(server as never);
|
||||
|
||||
const resume = registered.find((r) => r.name === "resume")!;
|
||||
await expect(resume.handler(new URL("resume://"))).rejects.toThrow(/Invalid resume URI/);
|
||||
});
|
||||
|
||||
it("resume-schema handler returns the static JSON schema as text", async () => {
|
||||
const { server, registered } = makeFakeServer();
|
||||
registerResources(server as never);
|
||||
|
||||
const resumeSchema = registered.find((r) => r.name === "resume-schema")!;
|
||||
const result = await resumeSchema.handler(new URL("resume://_meta/schema"));
|
||||
|
||||
expect(result.contents[0]?.uri).toBe("resume://_meta/schema");
|
||||
expect(result.contents[0]?.mimeType).toBe("application/json");
|
||||
|
||||
// Should round-trip through JSON.parse without throwing.
|
||||
expect(() => JSON.parse(result.contents[0]?.text)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { MCP_TOOL_NAME } from "./mcp-tool-names";
|
||||
import { TOOL_ANNOTATIONS } from "./tool-annotations";
|
||||
|
||||
describe("MCP_TOOL_NAME", () => {
|
||||
it("prefixes every tool name with reactive_resume_", () => {
|
||||
for (const name of Object.values(MCP_TOOL_NAME)) {
|
||||
expect(name.startsWith("reactive_resume_")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses unique values for every tool", () => {
|
||||
const values = Object.values(MCP_TOOL_NAME);
|
||||
expect(new Set(values).size).toBe(values.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("TOOL_ANNOTATIONS", () => {
|
||||
it("provides annotations for every registered tool", () => {
|
||||
for (const name of Object.values(MCP_TOOL_NAME)) {
|
||||
expect(TOOL_ANNOTATIONS[name]).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it("marks list/get tools as readOnly + idempotent + non-destructive", () => {
|
||||
const readOnlyTools = [
|
||||
MCP_TOOL_NAME.listResumes,
|
||||
MCP_TOOL_NAME.listResumeTags,
|
||||
MCP_TOOL_NAME.getResume,
|
||||
MCP_TOOL_NAME.getResumeAnalysis,
|
||||
MCP_TOOL_NAME.getResumeStatistics,
|
||||
];
|
||||
for (const name of readOnlyTools) {
|
||||
const annotations = TOOL_ANNOTATIONS[name];
|
||||
expect(annotations.readOnlyHint, name).toBe(true);
|
||||
expect(annotations.destructiveHint, name).toBe(false);
|
||||
expect(annotations.idempotentHint, name).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("marks deleteResume as destructive (but still idempotent)", () => {
|
||||
const annotations = TOOL_ANNOTATIONS[MCP_TOOL_NAME.deleteResume];
|
||||
expect(annotations.destructiveHint).toBe(true);
|
||||
expect(annotations.idempotentHint).toBe(true);
|
||||
expect(annotations.readOnlyHint).toBe(false);
|
||||
});
|
||||
|
||||
it("marks creation/import/duplicate as non-readonly and non-idempotent", () => {
|
||||
for (const name of [
|
||||
MCP_TOOL_NAME.createResume,
|
||||
MCP_TOOL_NAME.importResume,
|
||||
MCP_TOOL_NAME.duplicateResume,
|
||||
MCP_TOOL_NAME.patchResume,
|
||||
MCP_TOOL_NAME.updateResume,
|
||||
]) {
|
||||
const annotations = TOOL_ANNOTATIONS[name];
|
||||
expect(annotations.readOnlyHint, name).toBe(false);
|
||||
expect(annotations.idempotentHint, name).toBe(false);
|
||||
expect(annotations.destructiveHint, name).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("marks lockResume / unlockResume as idempotent and non-destructive", () => {
|
||||
for (const name of [MCP_TOOL_NAME.lockResume, MCP_TOOL_NAME.unlockResume]) {
|
||||
const annotations = TOOL_ANNOTATIONS[name];
|
||||
expect(annotations.idempotentHint, name).toBe(true);
|
||||
expect(annotations.destructiveHint, name).toBe(false);
|
||||
expect(annotations.readOnlyHint, name).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("declares no tools as open-world by default", () => {
|
||||
for (const annotations of Object.values(TOOL_ANNOTATIONS)) {
|
||||
expect(annotations.openWorldHint).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user