-
Notifications
You must be signed in to change notification settings - Fork 1.9k
test: Test for UI module (Part 1) #5703
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Thank you for following the naming conventions for pull request titles! 🙏 |
apps/web/modules/ui/components/file-input/components/video-settings.test.tsx
Fixed
Show fixed
Hide fixed
WalkthroughThis set of changes primarily introduces a large number of new unit test files across the UI components of the application, using Vitest and React Testing Library. The tests cover a wide range of components, including form elements, dialogs, dropdowns, avatars, badges, tables, editors, file inputs, and more. Several components also receive minor updates to their JSX attributes, such as adding Possibly related PRs
Tip ⚡️ Faster reviews with caching
Enjoy the performance boost—your workflow just got faster. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (7)
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 16
♻️ Duplicate comments (2)
apps/web/modules/ui/components/data-table/components/column-settings-dropdown.test.tsx (1)
55-55
: Same translation key issue as aboveThis is the same issue with using raw translation keys in tests.
apps/web/modules/ui/components/date-picker/index.test.tsx (1)
31-31
: Mock the translation mechanism for consistent testingSimilar to the previous file, the test is looking for raw translation keys. Consider implementing a translation mock to make tests more realistic.
🧹 Nitpick comments (47)
apps/web/modules/ui/components/avatars/index.test.tsx (1)
1-83
: Consider adding tests for different sizes and variants.While the current tests are solid, you could enhance coverage by testing different size props and avatar variants if they're supported by the components.
// Example additional test for PersonAvatar with custom size test("renders with custom size", () => { render(<PersonAvatar personId="test-person" size={60} />); const avatar = screen.getByTestId("boring-avatar-beam"); expect(avatar).toHaveAttribute("data-size", "60"); }); // Example additional test for ProfileAvatar with custom className test("renders with custom className", () => { render(<ProfileAvatar userId="user-123" className="custom-class" />); const avatar = screen.getByTestId("boring-avatar-bauhaus"); expect(avatar.parentElement).toHaveClass("custom-class"); });apps/web/modules/ui/components/file-input/components/video-settings.tsx (1)
122-128
: Consistency: Use standardizeddata-testid
attribute
The attribute is currently written asdata-testId
, which is inconsistent with HTML attribute naming and other components in the codebase (data-testid
). This may lead to unreliable selectors in tests.
Please update as follows:- data-testId="youtube-privacy-mode" + data-testid="youtube-privacy-mode"apps/web/modules/ui/components/file-input/components/uploader.tsx (1)
36-36
: Fix: Use standardizeddata-testid
attribute
The attribute is declared asdata-testId
, but should bedata-testid
for consistency and to avoid test selector failures:- data-testId="upload-file-label" + data-testid="upload-file-label"apps/web/modules/ui/components/client-logout/index.test.tsx (1)
11-21
: Comprehensive tests for this utility component.The tests verify both the component's effects (calling signOut) and its rendering behavior (returning null). You've covered the component's functionality completely.
For consistency with other test files, consider adding an
afterEach
cleanup step, although it's less critical here since the component renders null.describe("ClientLogout", () => { + afterEach(() => { + cleanup(); + }); test("calls signOut on render", () => {apps/web/modules/ui/components/data-table/lib/utils.test.ts (1)
4-23
: Consider adding tests for edge cases.The current test covers a single scenario with specific mock values. Consider adding tests for different input scenarios, such as when getStart returns 0 or negative values.
apps/web/modules/ui/components/file-input/lib/utils.test.ts (1)
130-140
: Duplicate test cases forcheckForYoutubePrivacyMode
These tests (lines 130-140) duplicate the existing tests in lines 115-128. Both sets verify the same functionality with slightly different URLs. Consider consolidating these tests to avoid redundancy.
-test("returns true for youtube-nocookie.com URLs", () => { - expect(checkForYoutubePrivacyMode("https://www.youtube-nocookie.com/embed/123")).toBe(true); -}); - -test("returns false for regular youtube.com URLs", () => { - expect(checkForYoutubePrivacyMode("https://www.youtube.com/watch?v=123")).toBe(false); -}); - -test("returns false for non-YouTube URLs", () => { - expect(checkForYoutubePrivacyMode("https://www.example.com")).toBe(false); -});apps/web/modules/ui/components/error-component/index.test.tsx (1)
20-25
: Consider using a more specific selector for the iconUsing
[aria-hidden='true']
as a selector might match multiple elements that are not related to the error icon. Consider adding a test ID to the icon in the component and using that for more precise targeting.apps/web/modules/ui/components/file-input/index.test.tsx (2)
35-39
: Translation keys in text assertionsSimilar to the ErrorComponent test, you're checking for translation keys ("common.image", "common.video") rather than actual translated text. Consider mocking the translation function or using test IDs for more reliable assertions.
17-75
: Consider adding error handling testsThe test suite covers basic functionality well, but there are no tests for error scenarios such as:
- File upload failure
- Invalid file types
- Network errors during upload
Consider adding tests for these scenarios to ensure the component handles errors gracefully.
apps/web/modules/ui/components/file-input/lib/actions.test.ts (1)
35-48
: Enhance HEIC conversion test with additional assertions.The test verifies the basic functionality, but it could be strengthened with additional assertions.
Consider these enhancements:
test("converts heic file to jpg", async () => { const file = new File(["test"], "test.heic", { type: "image/heic" }); // Mock arrayBuffer method file.arrayBuffer = vi.fn().mockResolvedValue(new ArrayBuffer(10)); const resultFile = await convertHeicToJpegAction({ file }); // Check the result is a File object with expected properties if (resultFile instanceof File) { expect(resultFile.name).toBe("test.jpg"); expect(resultFile.type).toBe("image/jpeg"); + // Verify heic-convert was called + const heicConvert = require("heic-convert").default; + expect(heicConvert).toHaveBeenCalledTimes(1); + } else { + throw new Error("Expected result to be a File object"); } });apps/web/modules/ui/components/editor/components/auto-link-plugin.test.tsx (1)
6-34
: Consider refactoring regex matchers for improved maintainability.The URL and email regex patterns are quite complex and could be moved to a separate file or utility if they're used elsewhere in the application.
Additionally, consider adding explicit naming for the matchers instead of relying on array indices:
-const matchers = [ +const matchers = { + urlMatcher: (text) => { const match = URL_MATCHER.exec(text); return ( match && { index: match.index, length: match[0].length, text: match[0], url: match[0], } ); }, + emailMatcher: (text) => { const match = EMAIL_MATCHER.exec(text); return ( match && { index: match.index, length: match[0].length, text: match[0], url: `mailto:${match[0]}`, } ); }, +};This would allow you to reference them directly by name in tests rather than by array index.
apps/web/modules/ui/components/connect-integration/index.test.tsx (2)
16-20
: Consider enhancing the useSearchParams mock for broader test coverage.The current mock always returns null for any parameter. Consider adding tests with different parameter values to ensure the component handles various routing scenarios correctly.
vi.mock("next/navigation", () => ({ useSearchParams: vi.fn(() => ({ - get: vi.fn((param) => null), + get: vi.fn((param) => { + // You can add more sophisticated parameter handling here + return null; + }), })), }));
56-87
: Consider using a more maintainable approach for mocking integration details.The current implementation uses hard-coded values for each integration type. This could become difficult to maintain if the actual implementation changes.
vi.mock("./lib/utils", () => ({ - getIntegrationDetails: vi.fn((type, t) => { - const details = { - googleSheets: { - text: "Google Sheets Integration Description", - docsLink: "https://formbricks.com/docs/integrations/google-sheets", - connectButtonLabel: "Connect with Google Sheets", - notConfiguredText: "Google Sheet integration is not configured", - }, - airtable: { - text: "Airtable Integration Description", - docsLink: "https://formbricks.com/docs/integrations/airtable", - connectButtonLabel: "Connect with Airtable", - notConfiguredText: "Airtable integration is not configured", - }, - notion: { - text: "Notion Integration Description", - docsLink: "https://formbricks.com/docs/integrations/notion", - connectButtonLabel: "Connect with Notion", - notConfiguredText: "Notion integration is not configured", - }, - slack: { - text: "Slack Integration Description", - docsLink: "https://formbricks.com/docs/integrations/slack", - connectButtonLabel: "Connect with Slack", - notConfiguredText: "Slack integration is not configured", - }, - }; - - return details[type]; - }), + getIntegrationDetails: vi.fn((type, t) => { + // Create a dynamic response based on the type + return { + text: `${type} Integration Description`, + docsLink: `https://formbricks.com/docs/integrations/${type}`, + connectButtonLabel: `Connect with ${type.charAt(0).toUpperCase() + type.slice(1)}`, + notConfiguredText: `${type} integration is not configured`, + }; + }), }));apps/web/modules/ui/components/data-table/components/data-table-settings-modal-item.test.tsx (2)
34-34
: Avoid type casting toany
in tests.Using
any
type bypasses TypeScript's type checking, which could hide potential type errors. Consider creating proper mock objects that match the expected types.- render(<DataTableSettingsModalItem column={mockColumn as any} />); + render(<DataTableSettingsModalItem column={mockColumn as Column<unknown>} />);You'll need to import the appropriate Column type and define your mock objects to match the expected structure.
Also applies to: 49-49, 61-61, 73-73, 95-95
100-114
: Add test for toggling visibility from hidden to visible.The current test only covers toggling from visible to hidden. Consider adding a test for the reverse scenario.
test("toggles visibility from hidden to visible when switch is clicked", async () => { const toggleVisibilityMock = vi.fn(); const mockColumn = { id: "lastName", getIsVisible: vi.fn().mockReturnValue(false), toggleVisibility: toggleVisibilityMock, }; render(<DataTableSettingsModalItem column={mockColumn as any} />); const switchElement = screen.getByRole("switch"); await userEvent.click(switchElement); expect(toggleVisibilityMock).toHaveBeenCalledWith(true); });apps/web/modules/ui/components/color-picker/index.test.tsx (1)
93-106
: Improve the input change test for better accuracy.The current test simulates typing in the input, but due to how the mock is implemented, it might not accurately reflect the real component behavior. Consider updating the test to directly simulate the onChange event.
test("calls onChange when input value changes", async () => { const mockColor = "ff0000"; const mockOnChange = vi.fn(); const user = userEvent.setup(); render(<ColorPicker color={mockColor} />); const input = screen.getByTestId("hex-color-input"); - await user.type(input, "abc123"); + // Directly simulate the change event + await user.clear(input); + await user.type(input, "abc123"); // The onChange from the HexColorInput would be called // In a real scenario, this would be tested differently, but our mock simulates the onChange event expect(mockOnChange).toHaveBeenCalled(); + // We could also verify the specific value if our mock supported it });apps/web/modules/ui/components/data-table/components/column-settings-dropdown.test.tsx (1)
16-16
: Consider using a more type-safe approach for mockingThe
as any
type assertion bypasses TypeScript's type checking, which could hide potential type issues. Consider creating a more type-safe mock that implements the necessary parts of the column interface.- render(<ColumnSettingsDropdown column={mockColumn as any} setIsTableSettingsModalOpen={vi.fn()} />); + render(<ColumnSettingsDropdown + column={mockColumn as unknown as Column<unknown>} + setIsTableSettingsModalOpen={vi.fn()} + />);apps/web/modules/ui/components/date-picker/index.test.tsx (1)
75-101
: Consider simplifying the date formatting testThis test is quite complex with cleanup and re-rendering. It might be more maintainable to split it into separate tests or use a more direct approach to verify the formatting logic.
test("formats date correctly with ordinal suffixes", async () => { const mockUpdateSurveyDate = vi.fn(); const user = userEvent.setup(); const selectedDate = new Date(2023, 5, 15); // June 15, 2023 - render(<DatePicker date={null} updateSurveyDate={mockUpdateSurveyDate} />); - - // Click to open the calendar - await user.click(screen.getByText("common.pick_a_date")); - - // Simulate selecting a date (the mock Calendar will return June 15, 2023) - await user.click(screen.getByTestId("calendar-day")); - - // Check if updateSurveyDate was called with the expected date - expect(mockUpdateSurveyDate).toHaveBeenCalledWith(expect.any(Date)); - - // Check that the formatted date shows on the button after selection - // The button now should show "15th Jun, 2023" with the correct ordinal suffix - const day = selectedDate.getDate(); - const expectedSuffix = "th"; // 15th - const formattedDateWithSuffix = format(selectedDate, `d'${expectedSuffix}' MMM, yyyy`); - - // Re-render with the selected date since our component doesn't auto-update in tests - cleanup(); + // Directly test the component with a selected date + const day = selectedDate.getDate(); + const expectedSuffix = "th"; // 15th+ const formattedDateWithSuffix = format(selectedDate, `d'${expectedSuffix}' MMM, yyyy`); + render(<DatePicker date={selectedDate} updateSurveyDate={mockUpdateSurveyDate} />); expect(screen.getByText(formattedDateWithSuffix)).toBeInTheDocument(); });apps/web/modules/ui/components/array-response/index.test.tsx (2)
20-21
: Improve type safety when testing with mixed value typesThe type assertion to
string[]
for an array that contains non-string values (null, undefined, false) could mask potential issues. Consider using a more explicit approach that matches the component's actual type expectations.- const testValues = ["Item 1", "", "Item 3", null, undefined, false]; - const { container } = render(<ArrayResponse value={testValues as string[]} />); + // Use definite types that match component expectations + const testValues: (string | null | undefined | boolean)[] = ["Item 1", "", "Item 3", null, undefined, false]; + const { container } = render(<ArrayResponse value={testValues} />);
27-27
: Use a more resilient selector for DOM testingUsing a complex CSS selector to count rendered divs might be fragile if the component structure changes. Consider using a data-testid attribute in the component for more reliable testing.
- const renderedDivs = container.querySelectorAll(".my-1.font-normal.text-slate-700 > div"); + // Add a data-testid to the array items in the component + // Then use this in the test: + const renderedDivs = container.querySelectorAll("[data-testid='array-item']");apps/web/modules/ui/components/calendar/index.test.tsx (1)
76-89
: Consider enhancing the Chevron component testWhile you're checking that the components.Chevron property exists and is a function, the test could be more comprehensive by also verifying the actual rendering or behavior of the Chevron component when it's used.
test("provides custom Chevron component", () => { render(<Calendar />); // Check that DayPicker was called at least once expect(DayPicker).toHaveBeenCalled(); // Get the first call arguments const firstCallArgs = vi.mocked(DayPicker).mock.calls[0][0]; // Verify components prop exists and has a Chevron function expect(firstCallArgs).toHaveProperty("components"); expect(firstCallArgs.components).toHaveProperty("Chevron"); expect(typeof firstCallArgs.components.Chevron).toBe("function"); + + // Optionally, render the Chevron component and verify its output + const { container } = render(firstCallArgs.components.Chevron({ dir: 'left' })); + expect(container).toMatchSnapshot(); });apps/web/modules/ui/components/background-styling-card/index.test.tsx (1)
191-210
: Interactive behavior tests could be more assertiveThe tests for background and brightness changes verify that the components render but don't assert any actual state changes or callback results after clicking the mock buttons. Consider adding expectations that verify the specific outcomes of these interactions.
test("changes background when background selector is used", async () => { const user = userEvent.setup(); render( <BackgroundStylingCard open={true} setOpen={mockSetOpen} colors={mockColors} environmentId={mockEnvironmentId} isUnsplashConfigured={true} form={mockForm as any} /> ); const bgChangeButton = screen.getByTestId("mock-bg-change-button"); await user.click(bgChangeButton); - // Verify the component rendered correctly expect(screen.getByTestId("survey-bg-selector-tab")).toBeInTheDocument(); + // Verify that handleBgChange was called with the expected values + // This requires storing the mock function's invocation in the test + expect(screen.getByTestId("survey-bg-selector-tab")).toHaveAttribute("data-bg", "new-bg-value"); + expect(screen.getByTestId("survey-bg-selector-tab")).toHaveAttribute("data-bg-type", "color"); });Also applies to: 212-231
apps/web/modules/ui/components/alert-dialog/index.test.tsx (1)
116-132
: Default variant test is incompleteWhile this test verifies that the decline button renders with the default variant, it doesn't actually assert that the "ghost" variant is applied. Consider enhancing this test to verify the actual variant applied to the button.
test("uses ghost variant for decline button by default", () => { const render( <AlertDialog open={true} setOpen={vi.fn()} headerText="Test Header" mainText="Test Main Text" confirmBtnLabel="Confirm" declineBtnLabel="Decline" /> ); expect(screen.getByText("Decline")).toBeInTheDocument(); + // Mock the Button component to capture and verify the variant prop + // Or use a data-variant attribute in the Button implementation for testing + expect(screen.getByText("Decline").closest("[data-variant]")).toHaveAttribute("data-variant", "ghost"); });apps/web/modules/ui/components/checkbox/index.test.tsx (1)
53-63
: Visual element verification needs improvementTesting for the presence of any SVG is too generic and may pass even if an incorrect icon is displayed. Consider using a more specific selector or a test ID to ensure the correct check icon is rendered.
test("displays check icon when checked", async () => { const user = userEvent.setup(); render(<Checkbox aria-label="Test checkbox" />); const checkbox = screen.getByRole("checkbox", { name: "Test checkbox" }); await user.click(checkbox); - const checkIcon = document.querySelector("svg"); - expect(checkIcon).toBeInTheDocument(); + // Add a data-testid to the SVG in the Checkbox component + const checkIcon = screen.getByTestId("checkbox-check-icon"); + expect(checkIcon).toBeInTheDocument(); });apps/web/modules/ui/components/file-input/components/video-settings.test.tsx (1)
1-143
: Consider adding a test for YouTube privacy mode toggle functionalityThe component includes YouTube privacy mode toggle functionality as shown in the related code snippet, but there's no test for this feature in the current test suite.
Consider adding a test that verifies the privacy mode toggle works correctly:
test("toggles YouTube privacy mode when the toggle is clicked", async () => { const user = userEvent.setup(); const mockProps = { uploadedVideoUrl: "https://www.youtube.com/watch?v=VIDEO_ID", setUploadedVideoUrl: vi.fn(), onFileUpload: vi.fn(), videoUrl: "https://www.youtube.com/watch?v=VIDEO_ID", setVideoUrlTemp: vi.fn(), }; // Mock the checkbox component const mockToggle = vi.fn(); vi.mock("@/modules/ui/components/advanced-option-toggle", () => ({ AdvancedOptionToggle: ({ onToggle, ...props }: any) => ( <div data-testid={props["data-testId"]} onClick={() => onToggle()} > Privacy Toggle </div> ), })); render(<VideoSettings {...mockProps} />); const privacyToggle = screen.getByTestId("youtube-privacy-mode"); await user.click(privacyToggle); expect(mockProps.setUploadedVideoUrl).toHaveBeenCalledWith("https://www.youtube-nocookie.com/embed/VIDEO_ID"); expect(mockProps.onFileUpload).toHaveBeenCalledWith(["https://www.youtube-nocookie.com/embed/VIDEO_ID"], "video"); });apps/web/modules/ui/components/editor/components/add-variables-dropdown.test.tsx (2)
72-85
: Make variable button selection more robustThe current approach of finding a button by text content and then using
closest("button")
is brittle and depends on the exact DOM structure.Consider using a more direct selector approach:
- const variableButton = screen.getByText("{USER_NAME_VARIABLE}").closest("button"); - await user.click(variableButton!); + const variableItem = screen.getByText("{USER_NAME_VARIABLE}"); + await user.click(variableItem);Or better yet, add a data-testid attribute to your variable items in the component implementation for more reliable selection.
87-96
: Improve variable info element selectionThe test is using a generic regex pattern to find text elements, which might be fragile if the text content changes.
Consider using a more specific approach:
- const variableInfoElements = screen.getAllByText(/name_info/); + const variableInfoElements = screen.getAllByText((content) => + content.includes("name_info") || content.includes("Variable Info") + );Or better yet, add a data-testid attribute to the variable info elements in the component implementation.
apps/web/modules/ui/components/data-table/components/selection-column.test.tsx (1)
15-22
: Use optional chaining for callback.The onClick handler uses a condition check before calling
onCheckedChange
. Using optional chaining would be more concise and follow modern JavaScript best practices.- => onCheckedChange && onCheckedChange(!checked)}> + => onCheckedChange?.(!checked)}>🧰 Tools
🪛 Biome (1.9.4)
[error] 19-19: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
apps/web/modules/ui/components/environment-notice/index.test.tsx (1)
1-118
: Well-structured tests with good coverage of the main component functionality.The tests effectively verify the component's rendering for both production and development environments, checking both the displayed text and link attributes. The mocks are comprehensive and properly isolate the component under test.
Consider adding tests for error handling scenarios:
#!/bin/bash # Check if the component handles errors properly by examining the error boundary # Check for throws or error handling in the component code rg -A 3 -B 1 "throw new Error" apps/web/modules/ui/components/environment-notice/index.tsxapps/web/modules/ui/components/confirmation-modal/index.test.tsx (1)
1-250
: Comprehensive test suite with excellent coverage of component behavior.The tests thoroughly cover rendering, user interactions, and various prop combinations. Good job testing both the UI state and the callback behavior.
For even better coverage, consider adding:
- Tests for keyboard accessibility (e.g., pressing Enter or Escape keys)
- Tests for any custom CSS class props that might be supported
Example for keyboard accessibility:
+ test("handles escape key press", async () => { + const user = userEvent.setup(); + const mockSetOpen = vi.fn(); + const mockOnConfirm = vi.fn(); + + render( + <ConfirmationModal + title="Test Title" + open={true} + setOpen={mockSetOpen} + > + text="Test confirmation text" + buttonText="Confirm Action" + /> + ); + + await user.keyboard('{Escape}'); + + expect(mockSetOpen).toHaveBeenCalledWith(false); + });apps/web/modules/ui/components/card-arrangement-tabs/index.test.tsx (2)
72-90
: Good test for visual elements, but could be more robust.While the test verifies the presence of SVG icons, the element selection relies on DOM traversal with
closest("label")
andquerySelector("svg")
, which can be fragile if the component structure changes.Consider adding data-testid attributes to make the tests more resilient:
// In the component file -<svg>...</svg> +<svg data-testid="arrangement-icon-casual">...</svg> // Then in the test -expect(casualLabel?.querySelector("svg")).toBeInTheDocument(); +expect(screen.getByTestId("arrangement-icon-casual")).toBeInTheDocument();
1-71
: Good core functionality testing, consider adding accessibility tests.The tests cover the essential user interactions and states of the component. For a more complete test suite:
Add keyboard navigation tests to ensure accessibility:
+ test("supports keyboard navigation between tabs", async () => { + const user = userEvent.setup(); + const setActiveCardArrangement = vi.fn(); + + render( + <CardArrangementTabs + surveyType="link" + activeCardArrangement="straight" + setActiveCardArrangement={setActiveCardArrangement} + /> + ); + + // Focus on the first radio button + const straightInput = screen.getByRole("radio", { name: "environments.surveys.edit.straight" }); + straightInput.focus(); + + // Press right arrow to move to next option + await user.keyboard('{ArrowRight}'); + + // Check if focus moved to the next radio + const casualInput = screen.getByRole("radio", { name: "environments.surveys.edit.casual" }); + expect(casualInput).toHaveFocus(); + + // Activate with space key + await user.keyboard(' '); + expect(setActiveCardArrangement).toHaveBeenCalledWith("casual", "link"); + });apps/web/modules/ui/components/data-table/components/data-table-header.test.tsx (1)
122-166
: Test the table settings modal opening functionality.The component accepts a
setIsTableSettingsModalOpen
function, but there's no test verifying it gets called when column settings are accessed.Add a test case for this functionality:
+ test("opens table settings modal when column settings are accessed", async () => { + const user = userEvent.setup(); + const setIsTableSettingsModalMock = vi.fn(); + const mockHeader = createMockHeader({ + id: "name", // Use a column that would show settings + }); + + render( + <table> + <thead> + <tr> + <DataTableHeader + header={mockHeader as any} + setIsTableSettingsModalOpen={setIsTableSettingsModalMock} + /> + </tr> + </thead> + </table> + ); + + // Find and click the column settings button if it exists in the component + const settingsButton = screen.getByRole("button", { name: /column settings/i }); + await user.click(settingsButton); + + expect(setIsTableSettingsModalMock).toHaveBeenCalledWith(true); + });apps/web/modules/ui/components/data-table/components/data-table-settings-modal.test.tsx (1)
110-137
: Test description doesn't match assertionThe test name suggests it verifies that
handleDragEnd
is called when a drag ends, but the assertion on line 136 verifies that it's not called. Consider either:
- Renaming the test to "doesn't call handleDragEnd with custom events" to match the assertion
- Modifying the test to better simulate the actual DndKit event that would trigger the handler
- test("calls handleDragEnd when drag ends", async () => { + test("doesn't call handleDragEnd with custom events", async () => {apps/web/modules/ui/components/code-block/index.test.tsx (1)
8-9
: Remove unnecessary commentThis empty comment line serves no purpose and should be removed.
-// Import toast -apps/web/modules/ui/components/data-table/components/data-table-toolbar.test.tsx (1)
59-64
: Consider using data-testid attributes for more robust element selection.Currently, the tests find buttons by selecting SVG elements with class names like
.lucide-settings
and.lucide-move-vertical
, then using.closest("div")
. This approach is fragile and could break if the icon library changes or the DOM structure is modified.Add data-testid attributes to the buttons in the component for more reliable selection:
// In the data-table-toolbar.tsx component - <div className="..." > + <div className="..." data-testid="settings-button"> <Settings className="lucide-settings..." /> </div>
Then update the tests to use these attributes:
- const settingsIcon = document.querySelector(".lucide-settings"); - const settingsButton = settingsIcon?.closest("div"); + const settingsButton = screen.getByTestId("settings-button");Also applies to: 89-96, 121-128, 154-162, 188-196
apps/web/modules/ui/components/form/index.test.tsx (2)
56-58
: Consider adding cleanup to the useEffect.When setting an error in useEffect, consider adding a cleanup function to reset it when the component unmounts, which would better represent typical React patterns.
useEffect(() => { form.setError("username", { type: "required", message: "Username is required" }); + return () => { + form.clearErrors("username"); + }; }, [form]);
82-124
: Consider adding test for absence of error message.The current tests verify that error messages display correctly when errors exist, but there's no test to verify that error messages aren't displayed when no errors are present.
Consider adding a test like:
test("FormError doesn't render content when there's no error", () => { render(<TestForm />); // The FormError is in the DOM but should not display any text const formErrorElement = document.querySelector("form div:last-child"); expect(formErrorElement).toBeInTheDocument(); expect(formErrorElement).toBeEmptyDOMElement(); });apps/web/modules/ui/components/delete-dialog/index.test.tsx (1)
118-157
: Consider consolidating the save button tests.The tests for the save button functionality are split between checking the button text and verifying the callback behavior. Consider consolidating these tests or making their separation more explicit in the test names.
Consider renaming the tests to make the distinction clearer:
- test("shows save button when useSaveInsteadOfCancel is true", () => { + test("renders save button instead of cancel when useSaveInsteadOfCancel is true", () => {- test("calls onSave when save button is clicked with useSaveInsteadOfCancel", async () => { + test("triggers onSave callback when save button is clicked", async () => {apps/web/modules/ui/components/data-table/components/selected-row-settings.test.tsx (2)
125-160
: Unused import and direct DOM querying.The test imports
rerender
but doesn't use it. Also, it usesdocument.querySelector
instead of React Testing Library's query methods to find the trash icon.- const { rerender } = render( + render(- const trashIcon = document.querySelector(".lucide-trash2"); + const trashIcon = screen.getByTestId("trash-icon");This would require adding a data-testid attribute to the trash icon in the component:
<TrashIcon data-testid="trash-icon" />
152-160
: Consider testing through user interactions.The test directly calls the mock functions rather than simulating user interactions, which doesn't fully test the component's behavior from the user's perspective.
Instead of directly calling the mock functions, consider testing the behavior through simulated user interactions:
const deleteButton = screen.getByTestId("delete-button"); await user.click(deleteButton); // Then in a different test or after the dialog confirmation: const confirmButton = screen.getByTestId("confirm-delete"); await user.click(confirmButton); // Then verify the mocks were called expect(deleteActionMock).toHaveBeenCalledWith("test-id-123"); expect(deleteRowsMock).toHaveBeenCalledWith(["test-id-123"]);This approach requires adding data-testid attributes to the relevant buttons in the component.
apps/web/modules/ui/components/background-styling-card/survey-bg-selector-tab.test.tsx (2)
6-27
: Consider using non-sensitive placeholder values in mocks.The mock constants include keys named "mock-encryption-key" and various client secrets. Even though these are just mock values for tests, it's safer to use generic placeholders like "test-value" rather than naming them as encryption keys or secrets to avoid any confusion.
- ENCRYPTION_KEY: "mock-encryption-key", - ENTERPRISE_LICENSE_KEY: "mock-enterprise-license-key", + ENCRYPTION_KEY: "test-encryption-value", + ENTERPRISE_LICENSE_KEY: "test-license-value",
18-19
: Fix inconsistent mock value format.The AZUREAD_CLIENT_SECRET value is truncated to "test-azure" which is inconsistent with other mock values that follow a more complete pattern (like "test-azuread-client-id").
- AZUREAD_CLIENT_SECRET: "test-azure", + AZUREAD_CLIENT_SECRET: "test-azuread-client-secret",apps/web/modules/ui/components/editor/components/editor.test.tsx (2)
59-71
: Review the LexicalComposer mock implementation.The comment "Fix the mock to correctly set the className for isInvalid" suggests there was a previous issue with this mock. Consider documenting why this special handling is needed or if there's a cleaner approach.
127-133
: Make test assertion more explicit.The test checks that the markdownPlugin doesn't have a specific attribute value, but doesn't verify what value it should have. Consider making the assertion more explicit by checking for the exact expected value.
// Should have filtered out two list transformers - expect(markdownPlugin).not.toHaveAttribute("data-transformers-count", "7"); + // Assuming 5 is the expected count after filtering list transformers + expect(markdownPlugin).toHaveAttribute("data-transformers-count", "5");apps/web/modules/ui/components/card-styling-settings/index.test.tsx (2)
50-69
: Consider a more flexible approach to form field mocking.The mock FormField component directly ties field names to specific default values, which couples tests tightly to implementation details. If field names change, tests will break even if functionality remains the same.
A more flexible approach could pass the expected default values through the test component props:
vi.mock("@/modules/ui/components/form", () => ({ // ... other components FormField: ({ name, render }) => { - const field = { - value: - name === "roundness" - ? 8 - : name === "hideProgressBar" - ? false - : name === "isLogoHidden" - ? false - : "#ffffff", - onChange: vi.fn(), - }; + // Get default values from a context or props + const defaultValues = { + roundness: 8, + hideProgressBar: false, + isLogoHidden: false, + }; + const field = { + value: defaultValues[name] ?? "#ffffff", + onChange: vi.fn(), + }; return render({ field, fieldState: { error: null } }); }, // ... other components }));
216-225
: Enhance the isSettingsPage test.The current test only verifies that the title element is rendered, which would be true regardless of the isSettingsPage value. Consider adding assertions to verify the visual difference.
Use a DOM testing approach that can verify the rendered output has different styling when isSettingsPage is true versus false:
test("renders settings page styling when isSettingsPage is true", () => { - render(<TestComponent isSettingsPage={true} />); + // Render both variants for comparison + const { unmount } = render(<TestComponent isSettingsPage={false} />); + const regularTitle = screen.getByText("environments.surveys.edit.card_styling"); + const regularParent = regularTitle.closest('[data-testid="collapsible-trigger"]'); + unmount(); + + render(<TestComponent isSettingsPage={true} />); const titleElement = screen.getByText("environments.surveys.edit.card_styling"); + const settingsParent = titleElement.closest('[data-testid="collapsible-trigger"]'); - // In the CSS, when isSettingsPage is true, the text-sm class should be applied - // We ca 8000 n't directly check classes in the test, so we're checking the element is rendered expect(titleElement).toBeInTheDocument(); + + // Verify the containers have different testids or attributes when in settings page mode + expect(settingsParent).not.toEqual(regularParent); });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (74)
apps/web/modules/ee/whitelabel/email-customization/components/email-customization-settings.tsx
(3 hunks)apps/web/modules/survey/editor/components/recontact-options-card.tsx
(2 hunks)apps/web/modules/survey/editor/components/saved-actions-tab.tsx
(1 hunks)apps/web/modules/survey/editor/components/unsplash-images.tsx
(1 hunks)apps/web/modules/ui/components/additional-integration-settings/index.test.tsx
(1 hunks)apps/web/modules/ui/components/advanced-option-toggle/index.test.tsx
(1 hunks)apps/web/modules/ui/components/alert-dialog/index.test.tsx
(1 hunks)apps/web/modules/ui/components/alert/index.test.tsx
(1 hunks)apps/web/modules/ui/components/alert/index.tsx
(1 hunks)apps/web/modules/ui/components/array-response/index.test.tsx
(1 hunks)apps/web/modules/ui/components/array-response/index.tsx
(1 hunks)apps/web/modules/ui/components/avatars/index.test.tsx
(1 hunks)apps/web/modules/ui/components/background-styling-card/index.test.tsx
(1 hunks)apps/web/modules/ui/components/background-styling-card/index.tsx
(1 hunks)apps/web/modules/ui/components/background-styling-card/survey-bg-selector-tab.test.tsx
(1 hunks)apps/web/modules/ui/components/badge-select/index.test.tsx
(1 hunks)apps/web/modules/ui/components/badge/index.test.tsx
(1 hunks)apps/web/modules/ui/components/breadcrumb/index.test.tsx
(1 hunks)apps/web/modules/ui/components/button/index.test.tsx
(1 hunks)apps/web/modules/ui/components/calendar/index.test.tsx
(1 hunks)apps/web/modules/ui/components/calendar/index.tsx
(0 hunks)apps/web/modules/ui/components/card-arrangement-tabs/index.test.tsx
(1 hunks)apps/web/modules/ui/components/card-styling-settings/index.test.tsx
(1 hunks)apps/web/modules/ui/components/checkbox/index.test.tsx
(1 hunks)apps/web/modules/ui/components/client-logo/index.test.tsx
(1 hunks)apps/web/modules/ui/components/client-logout/index.test.tsx
(1 hunks)apps/web/modules/ui/components/code-action-form/index.test.tsx
(1 hunks)apps/web/modules/ui/components/code-block/index.test.tsx
(1 hunks)apps/web/modules/ui/components/code-block/index.tsx
(1 hunks)apps/web/modules/ui/components/color-picker/components/popover-picker.test.tsx
(1 hunks)apps/web/modules/ui/components/color-picker/index.test.tsx
(1 hunks)apps/web/modules/ui/components/confetti/index.test.tsx
(1 hunks)apps/web/modules/ui/components/confirm-delete-segment-modal/index.test.tsx
(1 hunks)apps/web/modules/ui/components/confirmation-modal/index.test.tsx
(1 hunks)apps/web/modules/ui/components/connect-integration/index.test.tsx
(1 hunks)apps/web/modules/ui/components/connect-integration/lib/utils.test.ts
(1 hunks)apps/web/modules/ui/components/custom-dialog/index.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/components/column-settings-dropdown.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/components/data-table-header.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/components/data-table-settings-modal-item.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/components/data-table-settings-modal.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/components/data-table-toolbar.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/components/selected-row-settings.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/components/selection-column.test.tsx
(1 hunks)apps/web/modules/ui/components/data-table/lib/utils.test.ts
(1 hunks)apps/web/modules/ui/components/date-picker/index.test.tsx
(1 hunks)apps/web/modules/ui/components/default-tag/index.test.tsx
(1 hunks)apps/web/modules/ui/components/delete-dialog/index.test.tsx
(1 hunks)apps/web/modules/ui/components/dev-environment-banner/index.test.tsx
(1 hunks)apps/web/modules/ui/components/dialog/index.test.tsx
(1 hunks)apps/web/modules/ui/components/dropdown-menu/index.test.tsx
(1 hunks)apps/web/modules/ui/components/editor/components/add-variables-dropdown.test.tsx
(1 hunks)apps/web/modules/ui/components/editor/components/auto-link-plugin.test.tsx
(1 hunks)apps/web/modules/ui/components/editor/components/editor-content-checker.test.tsx
(1 hunks)apps/web/modules/ui/components/editor/components/editor.test.tsx
(1 hunks)apps/web/modules/ui/components/editor/components/toolbar-plugin.test.tsx
(1 hunks)apps/web/modules/ui/components/editor/index.test.ts
(1 hunks)apps/web/modules/ui/components/editor/lib/example-theme.test.ts
(1 hunks)apps/web/modules/ui/components/empty-space-filler/index.test.tsx
(1 hunks)apps/web/modules/ui/components/environment-notice/index.test.tsx
(1 hunks)apps/web/modules/ui/components/environmentId-base-layout/index.test.tsx
(1 hunks)apps/web/modules/ui/components/error-component/index.test.tsx
(1 hunks)apps/web/modules/ui/components/file-input/components/uploader.test.tsx
(1 hunks)apps/web/modules/ui/components/file-input/components/uploader.tsx
(2 hunks)apps/web/modules/ui/components/file-input/components/video-settings.test.tsx
(1 hunks)apps/web/modules/ui/components/file-input/components/video-settings.tsx
(1 hunks)apps/web/modules/ui/components/file-input/index.test.tsx
(1 hunks)apps/web/modules/ui/components/file-input/index.tsx
(4 hunks)apps/web/modules/ui/components/file-input/lib/actions.test.ts
(1 hunks)apps/web/modules/ui/components/file-input/lib/utils.test.ts
(3 hunks)apps/web/modules/ui/components/file-upload-response/index.test.tsx
(1 hunks)apps/web/modules/ui/components/form/index.test.tsx
(1 hunks)apps/web/modules/ui/components/go-back-button/index.test.tsx
(1 hunks)apps/web/modules/ui/components/header/index.test.tsx
(1 hunks)
💤 Files with no reviewable changes (1)
- apps/web/modules/ui/components/calendar/index.tsx
🧰 Additional context used
🧠 Learnings (1)
apps/web/modules/ui/components/file-input/lib/utils.test.ts (1)
Learnt from: victorvhs017
PR: formbricks/formbricks#5592
File: apps/web/modules/survey/editor/components/hidden-fields-card.test.tsx:3-4
Timestamp: 2025-04-30T18:39:18.490Z
Learning: The Formbricks project uses a vitestSetup file that includes global mocks for toast functions from react-hot-toast, eliminating the need to mock them in individual test files.
🧬 Code Graph Analysis (9)
apps/web/modules/ui/components/client-logout/index.test.tsx (1)
apps/web/modules/ui/components/client-logout/index.tsx (1)
ClientLogout
(6-11)
apps/web/modules/ui/components/environment-notice/index.test.tsx (1)
apps/web/modules/ui/components/environment-notice/index.tsx (1)
EnvironmentNotice
(12-38)
apps/web/modules/ui/components/file-input/index.test.tsx (1)
packages/types/common.ts (1)
TAllowedFileExtension
(73-73)
apps/web/modules/ui/components/file-input/lib/utils.test.ts (2)
apps/web/modules/ui/components/file-input/lib/utils.ts (2)
getAllowedFiles
(14-75)checkForYoutubePrivacyMode
(77-85)packages/types/common.ts (1)
TAllowedFileExtension
(73-73)
apps/web/modules/ui/components/alert-dialog/index.test.tsx (2)
apps/web/modules/ui/components/alert-dialog/index.tsx (1)
AlertDialog
(19-55)apps/web/modules/ui/components/modal/index.tsx (1)
Modal
(107-137)
apps/web/modules/ui/components/array-response/index.test.tsx (1)
apps/web/modules/ui/components/array-response/index.tsx (1)
ArrayResponse
(5-19)
apps/web/modules/ui/components/code-block/index.test.tsx (1)
apps/web/modules/ui/components/code-block/index.tsx (1)
CodeBlock
(20-52)
apps/web/modules/ui/components/card-styling-settings/index.test.tsx (3)
packages/types/surveys/types.ts (1)
TSurveyType
(791-791)apps/web/lib/survey/tests/__mock__/survey.mock.ts (1)
mockProject
(78-99)packages/js-core/src/types/config.ts (1)
TProjectStyling
(120-122)
apps/web/modules/ui/components/file-input/components/video-settings.test.tsx (1)
apps/web/modules/ui/components/file-input/components/video-settings.tsx (1)
VideoSettings
(22-132)
🪛 Biome (1.9.4)
apps/web/modules/ui/components/dialog/index.test.tsx
[error] 185-185: Avoid passing content using the dangerouslySetInnerHTML prop.
Setting content using code can expose users to cross-site scripting (XSS) attacks
(lint/security/noDangerouslySetInnerHtml)
[error] 194-194: Avoid passing content using the dangerouslySetInnerHTML prop.
Setting content using code can expose users to cross-site scripting (XSS) attacks
(lint/security/noDangerouslySetInnerHtml)
apps/web/modules/ui/components/data-table/components/selection-column.test.tsx
[error] 19-19: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
apps/web/modules/ui/components/dropdown-menu/index.test.tsx
[error] 158-158: Avoid passing content using the dangerouslySetInnerHTML prop.
Setting content using code can expose users to cross-site scripting (XSS) attacks
(lint/security/noDangerouslySetInnerHtml)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: Build Formbricks-web / Build Formbricks-web
- GitHub Check: Run E2E Tests / Run E2E Tests
- GitHub Check: Run Unit Tests / Unit Tests
- GitHub Check: SonarQube
- GitHub Check: Validate Docker Build
- GitHub Check: Analyze (javascript)
🔇 Additional comments (128)
apps/web/modules/ui/components/avatars/index.test.tsx (4)
1-21
: Well-structured test setup with proper mocking!The test setup correctly mocks both the
boring-avatars
package and Next.jsImage
component, making it easier to test the rendering logic without external dependencies. This approach effectively isolates the components under test.
22-26
: Good test organization with proper cleanup.Using
afterEach(cleanup)
ensures that each test runs in isolation without interference from previous test runs, which prevents potential false positives.
27-44
: PersonAvatar tests verify core functionality.The tests correctly verify that the PersonAvatar component renders with the expected props and handles different personIds appropriately.
46-82
: Comprehensive ProfileAvatar test cases.Good job covering all the main rendering scenarios for ProfileAvatar: no imageUrl, null imageUrl, and valid imageUrl cases. The tests verify both the fallback to Boring Avatar and the proper rendering of the Image component with correct attributes.
apps/web/modules/survey/editor/components/saved-actions-tab.tsx (1)
67-67
: Class ordering looks good.The reordering of Tailwind CSS classes from
"mt-4 mb-2 font-semibold"
to"mb-2 mt-4 font-semibold"
provides better consistency in class ordering across the codebase without affecting the rendered output.apps/web/modules/survey/editor/components/recontact-options-card.tsx (2)
124-124
: Class ordering looks good.The reordering of padding Tailwind CSS classes from
pr-5 pl-2
topl-2 pr-5
provides better consistency in class ordering across the codebase.
259-259
: Class ordering looks good.The reordering of margin Tailwind CSS classes from
mr-2 ml-2
toml-2 mr-2
follows the consistent approach to class ordering being implemented across the codebase.apps/web/modules/ee/whitelabel/email-customization/components/email-customization-settings.tsx (3)
196-196
: Class ordering looks good.The reordering of margin Tailwind CSS classes from
mt-2 mb-6
tomb-6 mt-2
provides better consistency in class ordering across the codebase.
259-259
: Class ordering looks good.The reordering of padding Tailwind CSS classes provides better consistency in class ordering across the codebase.
287-287
: Class ordering looks good.The reordering of margin Tailwind CSS classes from
mt-4 mb-6
tomb-6 mt-4
follows the consistent approach to class ordering being implemented across the codebase.apps/web/modules/survey/editor/components/unsplash-images.tsx (1)
235-237
: Approve: Stable test selector added
Thedata-testid="unsplash-select-button"
attribute on the "Load More" button provides a reliable test selector without impacting functionality.apps/web/modules/ui/components/code-block/index.tsx (1)
37-37
: Approve: Test ID for copy icon
Addingdata-testid="copy-icon"
enables precise selection in tests without altering component behavior.apps/web/modules/ui/components/background-styling-card/index.tsx (1)
54-54
: Approve: Test ID on collapsible trigger
The addition ofdata-testid="background-styling-card-trigger"
supports robust testing of the trigger element, aligning with the PR's testability improvements.apps/web/modules/ui/components/environmentId-base-layout/index.test.tsx (1)
1-3
: Good cleanup of unused imports!Removing unused imports (
cleanup
,afterEach
, andbeforeEach
) improves code cleanliness without affecting functionality.apps/web/modules/ui/components/editor/index.test.ts (1)
1-14
: Well-structured module export verification tests!This test suite effectively verifies that the Editor module exports the expected components, ensuring the module's contract remains stable.
apps/web/modules/ui/components/array-response/index.tsx (1)
11-11
: Great improvement to React key implementation!Using a composite key (
${index}-${item}
) instead of just the array index enhances React's reconciliation process, especially when dealing with collections that might have duplicate values.apps/web/modules/ui/components/file-input/index.tsx (1)
240-240
: Consistent ordering of Tailwind CSS classesReordering the position utility classes from
absolute top-2 right-2
toabsolute right-2 top-2
maintains consistent styling patterns across the codebase.Also applies to: 258-258, 298-298, 314-314
apps/web/modules/ui/components/header/index.test.tsx (1)
1-26
: Well-structured test suite for the Header component!The tests effectively cover the major functionality of the Header component, including rendering the title and conditionally rendering the subtitle. Good job using the cleanup function to prevent test leakage.
apps/web/modules/ui/components/client-logout/index.test.tsx (1)
6-9
: Good approach for mocking the next-auth/react module.The mock implementation is clear and focused on what's needed for testing.
apps/web/modules/ui/components/file-upload-response/index.test.tsx (2)
6-16
: Clear and effective mocking of the file utility.The mock implementation provides appropriate responses for different test scenarios, which is good practice.
35-43
: Good job testing link attributes.Testing URL, target, and rel attributes ensures the component creates proper and secure external links.
apps/web/modules/ui/components/file-input/lib/utils.test.ts (1)
85-111
: Good addition of edge case tests forgetAllowedFiles
These additional tests are valuable as they cover important edge cases:
- Empty file array input
- Filtering files based on allowed extensions
- Handling files without extensions
The tests are thorough and well-structured, ensuring the function behaves correctly in various scenarios.
apps/web/modules/ui/components/file-input/index.test.tsx (2)
8-15
: Good mock setup for dependenciesThe mocks for file upload and utility functions are appropriate and help isolate the component under test. The implementation matches the expected behavior needed for the tests.
60-67
: Good test for multiple file handlingThe test for handling multiple files is well-structured and verifies an important feature of the component.
apps/web/modules/ui/components/connect-integration/lib/utils.test.ts (1)
4-50
: Well-structured tests for integration detailsThese tests comprehensively cover all supported integration types (Google Sheets, Airtable, Notion, Slack) and verify that the correct details are returned for each.
The use of a simple mock translation function is appropriate for testing the utility's logic. The test structure is clean and easy to understand.
apps/web/modules/ui/components/default-tag/index.test.tsx (1)
1-32
: Well-structured test suite with good coverage.The test suite for DefaultTag is well-organized and covers both styling and translation behavior effectively. The use of cleanup after each test ensures proper isolation.
One small suggestion to improve readability:
- expect(screen.getByText("common.default")).toBeInTheDocument(); + expect(screen.getByRole("div")).toHaveTextContent("common.default");apps/web/modules/ui/components/file-input/lib/actions.test.ts (1)
27-33
: Test for non-HEIC files is well-implemented.The test correctly verifies that non-HEIC files are returned unchanged.
apps/web/modules/ui/components/go-back-button/index.test.tsx (1)
16-46
: Comprehensive test suite for GoBackButton component.The tests cover all functionality comprehensively:
- Rendering with correct text
- Navigation behavior without a URL (using back)
- Navigation behavior with a URL (using push)
The use of afterEach for cleanup and mock reset is good practice.
Consider enhancing test resilience by using data-testid instead of text content:
- const button = screen.getByText("common.back"); + render(<GoBackButton data-testid="back-button" />); + const button = screen.getByTestId("back-button");This approach makes tests more resilient to text changes and internationalization.
apps/web/modules/ui/components/connect-integration/index.test.tsx (3)
102-109
: LGTM - Good coverage of integration details rendering.The test effectively verifies that the component correctly renders the integration details, including description text, button label, and image attributes.
111-115
: LGTM - Good test for disabled state.This test correctly verifies that the button is disabled when the integration is not enabled.
117-125
: LGTM - Good user interaction testing.This test effectively verifies that the handleAuthorization callback is called when the button is clicked.
apps/web/modules/ui/components/data-table/components/data-table-settings-modal-item.test.tsx (2)
6-20
: LGTM - Well-structured mock for dnd-kit/sortable.The mock implementation correctly imports the actual module and overrides only the necessary parts, providing stable values for testing.
27-40
: LGTM - Good coverage of different column types.The tests effectively verify that the component renders the correct labels for different column types, including standard columns, special columns, and survey question columns.
Also applies to: 42-52, 54-64, 66-76, 78-98
apps/web/modules/ui/components/color-picker/index.test.tsx (3)
6-26
: LGTM - Good mock implementation for HexColorInput.The mock correctly simulates the behavior of the real component, including handling of color, onChange, and disabled props.
28-47
: LGTM - Good mock implementation for PopoverPicker.The mock correctly simulates the behavior of the real component, including handling of color, onChange, and disabled props.
54-67
: LGTM - Good coverage of component functionality.The tests effectively verify that the component renders correctly with the provided color, applies custom container classes, handles disabled state, and responds to user interactions.
Also applies to: 69-78, 80-91, 108-120
apps/web/modules/ui/components/dev-environment-banner/index.test.tsx (4)
6-11
: LGTM - Clear and concise translation mock.The mock for the useTranslate hook is simple and effective for testing purposes.
18-33
: LGTM - Good test for development environment banner.The test correctly verifies that the banner is displayed with the appropriate text and styling when the environment type is "development".
35-48
: LGTM - Good test for non-development environment.The test correctly verifies that the banner is not displayed when the environment type is not "development".
13-16
: LGTM - Good test setup with proper cleanup.The test suite is well-structured with appropriate cleanup after each test to ensure test isolation.
apps/web/modules/ui/components/confetti/index.test.tsx (3)
1-22
: Well-structured test setup with effective mocksThe test setup effectively mocks both the
react-confetti
component and theuseWindowSize
hook to isolate the component under test. This approach allows you to test the component's behavior without depending on actual window dimensions or the real confetti implementation.
24-39
: Good coverage of default props behaviorThis test correctly verifies that all expected props are passed to the confetti component with their default values. The assertions are comprehensive and test each attribute individually.
41-48
: Well-implemented custom colors testThe test for custom colors properly verifies that the component accepts and forwards custom color arrays to the underlying confetti implementation.
apps/web/modules/ui/components/date-picker/index.test.tsx (1)
8-18
: Well-structured Calendar mockThe mock implementation of the Calendar component effectively simulates the date-picking behavior without requiring the actual component's implementation details.
apps/web/modules/ui/components/array-response/index.test.tsx (2)
10-17
: Good basic test for rendering array valuesThis test effectively verifies that each array item is correctly rendered in the document.
39-42
: Good edge case testing for empty arraysThe test for empty arrays is important and correctly verifies that the component handles this edge case appropriately.
apps/web/modules/ui/components/advanced-option-toggle/index.test.tsx (1)
1-125
: Well-structured and comprehensive test suite for AdvancedOptionToggleThis is a thorough test suite that covers all the key functionality of the AdvancedOptionToggle component, including:
- Basic rendering with required props
- Toggle callback functionality
- Conditional children rendering
- Border styling options
- Disabled state handling
Good job implementing proper cleanup after each test and using clear test descriptions. The tests are well-organized and follow best practices.
apps/web/modules/ui/components/calendar/index.test.tsx (1)
7-28
: Excellent mocking approach for isolating component testsThe mock implementation for react-day-picker is very well done. You've created a comprehensive mock that correctly simulates the behavior of the DayPicker component while providing test hooks for verifying props and callbacks. This is the right approach for testing a wrapper component that primarily configures another component.
apps/web/modules/ui/components/color-picker/components/popover-picker.test.tsx (2)
6-14
: Clever mock implementation for useClickOutside hookThe mock implementation for the useClickOutside hook is clever and allows for testing the component's behavior. The approach of storing the callback on the ref's current value makes it accessible for testing.
25-102
: Comprehensive test coverage for PopoverPicker componentThe test suite thoroughly covers all key functionality of the PopoverPicker component:
- Color block rendering with correct background color
- Opening the picker on click
- Color selection and onChange callback
- Disabled state styling and behavior
Good job using userEvent for interaction testing and properly cleaning up after each test.
apps/web/modules/ui/components/editor/lib/example-theme.test.ts (2)
52-66
: Great approach for ensuring consistent naming conventionThis test is excellent! It ensures that all string values in the theme object follow the consistent naming convention with the "fb-editor-" prefix. This type of test helps maintain code quality and prevents inconsistencies from creeping into the theme over time.
1-51
: Complete coverage of theme structure and valuesThe tests thoroughly cover all aspects of the theme object, including:
- Basic theme properties
- Heading styles
- List styles
- Text formatting styles
- Link and image styles
- Directional styles
This approach with specific assertions is clear and maintainable.
apps/web/modules/ui/components/background-styling-card/index.test.tsx (4)
1-55
: Comprehensive test setup with thorough mockingThe test file correctly mocks all dependencies including translation hooks, animation hooks, and complex components. This isolates the component under test and ensures that we're testing the component's logic rather than its dependencies.
71-91
: Well-structured closed state testThe test correctly verifies that when the card is closed, the title and description are visible but the actual content (background selector and slider) is not rendered in the DOM. This confirms the collapsible behavior functions properly.
148-149
: Good test for disabled state stylingThe test correctly verifies that the disabled state adds the expected CSS class for cursor styling, which is an important visual indicator to users that the component is not interactive.
171-189
: Thorough verification of disabled interaction preventionThe test properly checks that clicking on the trigger doesn't call the setOpen function when the component is in a disabled state, ensuring the disabled state properly prevents user interaction.
apps/web/modules/ui/components/alert-dialog/index.test.tsx (3)
7-26
: Effective mocking of Modal and translationsThe mocks for the Modal component and translation hook are well implemented, providing just enough functionality to test the AlertDialog component in isolation.
34-80
: Comprehensive test for all props and interactionsThis test effectively verifies that:
- The Modal receives the correct props
- Main text and buttons are displayed correctly
- Button clicks trigger the expected callbacks
Good use of userEvent for simulating user interactions.
96-114
: Good default behavior verificationThe test correctly verifies that when no onConfirm handler is provided, clicking the confirm button sets open to false, which is important default behavior for a modal dialog.
apps/web/modules/ui/components/additional-integration-settings/index.test.tsx (4)
11-30
: Thorough test of rendered elementsGood verification that all expected text elements are rendered in the component, ensuring the UI is complete.
32-54
: Good verification of initial checkbox statesThis test correctly verifies that checkboxes reflect their initial state based on props. The test uses proper assertions to check each checkbox's state individually.
56-86
: Comprehensive test of all checkbox interactionsThe test thoroughly verifies that clicking each checkbox calls the appropriate setter function with the correct boolean value. This ensures the component correctly updates its state based on user interactions.
88-110
: Well-designed toggle state verificationThis test verifies that toggling checkboxes correctly flips boolean values (true→false and false→true), demonstrating proper handling of both initial states.
apps/web/modules/ui/components/checkbox/index.test.tsx (3)
11-17
: Good basic rendering testThe test properly verifies that the checkbox renders and is unchecked by default, using accessible queries which is a best practice.
19-32
: Well-implemented interaction testThe test correctly verifies that the checkbox can be checked and unchecked through user interaction, demonstrating the component's core functionality.
41-51
: Good disabled state verificationThe test correctly verifies that a disabled checkbox cannot be checked through user interaction, which is important for accessibility and user experience.
apps/web/modules/ui/components/editor/components/editor-content-checker.test.tsx (6)
1-27
: LGTM - Well-structured mocks for Lexical context and functionsThe test setup effectively mocks Lexical dependencies with the appropriate implementation details needed for testing. The mocks properly simulate the editor context and root node for different test scenarios.
28-33
: LGTM - Good test organization with proper cleanupThe test suite follows best practices by using
afterEach
to clean up after tests and clear mocks, ensuring test isolation.
34-44
: LGTM - Clear test for empty editor detectionThis test properly verifies that the component calls
onEmptyChange
withtrue
when the editor is empty, and includes a useful comment about the initial render behavior.
46-62
: LGTM - Thorough unmount cleanup verificationGood test for ensuring the component properly unregisters its update listener on unmount, which prevents memory leaks and unnecessary updates.
64-76
: LGTM - Non-empty content detection testThe test correctly mocks a non-empty editor state and verifies the appropriate callback is made with the expected value.
78-91
: LGTM - Whitespace handling verificationThis test confirms that content with only whitespace is correctly treated as empty, which is an important edge case to verify.
apps/web/modules/ui/components/file-input/components/video-settings.test.tsx (7)
1-38
: LGTM - Comprehensive mocking of video utility functionsThe test file properly mocks all external dependencies, including URL validation, conversion functions, and toast notifications. The mock implementations handle different video platforms correctly.
39-44
: LGTM - Good test isolation with cleanupThe test suite follows best practices by using
afterEach
to clean up rendered components and reset mocks between tests.
45-59
: LGTM - Input field rendering testThis test correctly verifies that the component renders an input field with the provided URL value.
61-88
: LGTM - Conditional button rendering testsGood tests for verifying the component's conditional rendering logic of Add/Remove buttons based on the relationship between
uploadedVideoUrl
andvideoUrl
.
90-103
: LGTM - Button disabled state verificationThis test properly checks that the Add button is disabled when the URL input is empty, preventing invalid submissions.
105-124
: LGTM - User interaction test for Remove buttonThis test effectively simulates user interaction and verifies that the correct handler functions are called with expected arguments when the Remove button is clicked.
126-142
: LGTM - Unsupported URL warning testThis test successfully verifies that warnings are displayed for unsupported video platform URLs, which is an important validation feature.
apps/web/modules/ui/components/editor/components/add-variables-dropdown.test.tsx (5)
1-21
: LGTM - Clean component mocking approachThe test file effectively mocks UI components to isolate the component under test. The mocks are simple and focused on structure rather than implementation details.
22-26
: LGTM - Proper test cleanupGood practice using
afterEach
to clear mocks between tests, ensuring test isolation.
27-41
: LGTM - Basic rendering verificationThis test thoroughly checks that the dropdown renders correctly with variables, verifying both structural components and variable content.
43-53
: LGTM - Conditional rendering test for text editor modeGood test for verifying the mobile view rendering when
isTextEditor
is true, including class checks for responsive behavior.
55-70
: LGTM - Careful test isolation with unmountThis test properly creates an isolated render and unmounts it afterward, avoiding interference with other tests. The approach of checking DOM elements by class selector is appropriate here.
apps/web/modules/ui/components/badge/index.test.tsx (6)
1-9
: LGTM - Clean test setup with proper cleanupThe test file follows best practices with proper imports and test cleanup using
afterEach
.
10-14
: LGTM - Basic rendering verificationSimple test ensuring the component renders with the given text content.
15-35
: LGTM - Thorough type class testingThis test effectively uses
rerender
to test all badge types (warning, success, error, gray) with a single test, verifying the correct classes are applied in each case.
37-52
: LGTM - Comprehensive size class testingSimilar to the type testing, this efficiently tests all size variants (tiny, normal, large) by reusing the test component with different props.
54-62
: LGTM - Custom class and role attribute testsGood coverage of additional props like custom className and role attributes, ensuring they're properly applied to the rendered component.
64-74
: LGTM - Comprehensive combined props testThis test effectively verifies that multiple props work together correctly, with all expected classes being applied simultaneously.
apps/web/modules/ui/components/custom-dialog/index.test.tsx (6)
1-4
: Good choice of testing libraries.Using React Testing Library with Vitest provides a solid foundation for component testing, focusing on user interactions and component behavior.
6-26
: Well-structured component mocks.The mocks for
Modal
andButton
components are well-designed, capturing the necessary props and behavior needed for testing theCustomDialog
component in isolation.
28-43
: Good test coverage for basic rendering.These tests effectively verify the conditional rendering behavior based on the
open
prop, which is a critical aspect of the dialog's functionality.
67-87
: Comprehensive testing of button interactions.The tests for the OK button's callback functionality and the Cancel button's behavior (including conditional callback execution) are thorough and well-implemented.
122-132
: Complete coverage of button states.The tests for loading and disabled states ensure that the dialog properly handles these UI states, which is important for user experience during asynchronous operations.
114-120
:✅ Verification successful
Missing tolgee translation mock.
The test assumes tolgee (translation library) is mocked, but there's no explicit mock setup visible in this file. This may lead to inconsistent test behavior if the implicit mock changes.
🏁 Script executed:
#!/bin/bash # Check if there's a global tolgee mock in the test setup cd apps/web find . -type f -name '*.ts' -o -name '*.tsx' | xargs grep -l "vi.mock.*tolgee"Length of output: 6230
🏁 Script executed:
#!/bin/bash # Verify if tolgee is mocked globally in vitest setup grep -n "mock.*tolgee" -n apps/web/vitestSetup.tsLength of output: 138
No explicit tolgee mock needed—global mock covers all tests
The Vitest setup already mocks@tolgee/react
for every test suite, so individual files don’t need their own mock.• See apps/web/vitestSetup.ts (lines 50–52) for the global
vi.mock("@tolgee/react", …)
setup.apps/web/modules/ui/components/dropdown-menu/index.test.tsx (4)
1-26
: Well-organized test suite setup.The imports and test structure follow best practices, with proper cleanup after each test to ensure test isolation.
27-66
: Good testing of basic dropdown functionality.The tests effectively verify the core dropdown menu rendering behavior and group functionality, using proper assertions and user event simulation.
171-227
: Thorough testing of interactive elements.The tests for checkbox and radio group functionality are well-implemented, verifying both rendering and interaction behavior through simulated user events.
229-301
: Comprehensive submenu and icon testing.The tests effectively verify advanced dropdown features like submenus and icon rendering, ensuring the component handles complex structures correctly.
apps/web/modules/ui/components/dialog/index.test.tsx (1)
6-73
: Extensive and well-structured mocks.The mocks for Radix UI dialog components and Lucide React icons are thorough and well-implemented, facilitating isolated testing of the dialog components.
apps/web/modules/ui/components/data-table/components/selection-column.test.tsx (2)
6-23
: Good mocking approach.The mocking strategy for both the Tanstack table library and the Checkbox component is effective. Importing the actual module before overriding is a good practice for maintaining type safety.
🧰 Tools
🪛 Biome (1.9.4)
[error] 19-19: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
30-66
: Comprehensive column and checkbox testing.The tests effectively verify the column definition properties and the rendering behavior of both header and cell checkboxes, including their checked states based on row selection.
apps/web/modules/ui/components/button/index.test.tsx (1)
1-141
: Great comprehensive test suite for the Button component!The test suite thoroughly covers all aspects of the Button component including variants, sizes, states, event handling, and the buttonVariants utility function. The tests are well-organized, focused, and follow best practices.
apps/web/modules/ui/components/client-logo/index.test.tsx (1)
1-72
: Tests look comprehensive and well-structured.The test suite covers all the main features of the ClientLogo component, including:
- Logo rendering with proper URL encoding
- "Add logo" link rendering and URL construction
- Preview survey styling application
- Edge case handling for missing environmentId
The clean structure with descriptive test names and proper setup/cleanup makes this easy to maintain.
apps/web/modules/ui/components/code-action-form/index.test.tsx (3)
6-50
: Good approach to component mocking.The mocks effectively isolate the component under test by replacing complex dependencies with simplified versions that have testable interfaces. This makes the tests more reliable and less prone to breaking from changes in dependent components.
53-65
: Well-implemented test wrapper.Using a dedicated TestWrapper component with React Hook Form's FormProvider is an excellent pattern for testing form components that need context. This makes the tests more concise and focused on the component behavior rather than setup details.
67-114
: Thorough coverage of component states.The tests cover all important aspects of the component:
- Basic rendering and content verification
- Read-only state behavior
- Interactive/editable state behavior
The assertions properly check both presence of elements and their correct attributes.
apps/web/modules/ui/components/data-table/components/data-table-toolbar.test.tsx (2)
131-163
: Comprehensive testing of async functionality.The test properly verifies the refresh contacts functionality, including:
- Button presence
- Function call validation
- Success toast display
- Proper handling of resolved promises
This is a good example of testing asynchronous operations in React components.
165-197
: Good error handling test.Testing the error path for the async refresh operation ensures the component handles failures gracefully. This is an important aspect that's often overlooked in component tests.
apps/web/modules/ui/components/empty-space-filler/index.test.tsx (3)
7-20
: Effective mocking strategy for external dependencies.The mocks for the translation hook and Next.js Link component are well implemented, allowing the tests to focus on the component's logic without being affected by external behavior.
27-39
: Good use of mock data fixtures.Creating reusable mock environment objects with different states makes the tests more readable and maintainable, while ensuring consistent test data across different test cases.
41-168
: Excellent comprehensive test coverage of conditional rendering.The tests thoroughly cover all the possible combinations of:
- Different type props (table, response, tag, summary, default)
- Environment states (appSetupCompleted true/false)
- Optional props (emptyMessage, noWidgetRequired)
This ensures that all rendering paths are verified, which is crucial for a component with complex conditional logic.
apps/web/modules/ui/components/form/index.test.tsx (1)
1-124
: Well-structured test suite with good coverage.The test suite provides comprehensive coverage of the form components, including rendering, user input handling, error states, and styling verification. The use of test components to simulate different scenarios is a great approach.
apps/web/modules/ui/components/breadcrumb/index.test.tsx (3)
1-149
: Excellent comprehensive test suite for breadcrumb components.This test suite thoroughly covers all breadcrumb components, their rendering behavior, accessibility attributes, and styling. The tests for complete navigation structure and custom class applications are particularly valuable.
61-71
: Good testing of default separator.Well-structured test for verifying that the default separator contains an SVG element when no children are provided.
101-126
: Thorough integration test of the whole breadcrumb system.This test effectively verifies that all components work together correctly in a complete navigation structure, checking for proper text content and separator count.
apps/web/modules/ui/components/delete-dialog/index.test.tsx (2)
6-31
: Well-structured component mocks.Your mocks for Modal and Button components are well-designed, capturing the essential behaviors needed for testing while simplifying the implementation details.
159-179
: Good coverage of loading states.The tests for loading states verify both the delete and save buttons correctly show loading indicators when the respective operations are in progress.
apps/web/modules/ui/components/data-table/compon 67E6 ents/selected-row-settings.test.tsx (1)
8-13
: Good approach to mock toast functions.Mocking react-hot-toast at the module level is an effective way to verify toast notifications without dealing with the actual toast UI.
apps/web/modules/ui/components/alert/index.test.tsx (1)
1-135
: Well-structured and comprehensive test suite for the Alert componentThis test suite thoroughly covers all aspects of the Alert component including rendering, variants, sizes, and interactions. The tests are clear and well-organized.
apps/web/modules/ui/components/file-input/components/uploader.test.tsx (1)
1-87
: Comprehensive test coverage for the Uploader componentThe test suite effectively covers all the key functionality of the Uploader component, including rendering, file handling, accessibility attributes, and state management. Well-structured with good separation of concerns.
apps/web/modules/ui/components/editor/components/toolbar-plugin.test.tsx (3)
6-105
: Comprehensive mocking approach for Lexical editor environmentThe extensive mocking of the Lexical editor ecosystem is well-structured and thorough, enabling isolated testing of the toolbar plugin without dependencies on the actual editor implementation.
106-168
: Well-structured component mocksThe mocks for UI components and editor-related functionality are properly implemented, allowing the tests to focus on the plugin's behavior rather than implementation details of its dependencies.
169-256
: Effective test coverage for toolbar functionalityThe test suite covers the key aspects of the toolbar plugin including rendering, conditional display based on editability, variable handling, and toolbar item exclusion. The careful setup of mocks and test isolation ensures reliable test outcomes.
apps/web/modules/ui/components/background-styling-card/survey-bg-selector-tab.test.tsx (1)
109-273
: LGTM! Comprehensive test coverage.The test suite provides thorough coverage of the component's functionality, including:
- Tab rendering based on configuration
- Conditional display of Unsplash image tab
- Correct component rendering for each tab type
- Background change callback handling
- Proper initialization with background type
- Appropriate prop passing to child components
apps/web/modules/ui/components/editor/components/editor.test.tsx (1)
77-134
: LGTM! Well-structured test suite.The test suite effectively verifies multiple aspects of the Editor component:
- Default rendering
- Custom height styling
- Variables propagation
- Editable state toggling
- Content checker integration
- List functionality configuration
The isolation of the component through comprehensive mocking is well-implemented.
apps/web/modules/ui/components/card-styling-settings/index.test.tsx (1)
131-226
: LGTM! Good test coverage of component functionality.The test suite effectively covers:
- Conditional rendering based on the open state
- Form control rendering and interaction
- Color picker components
- Slider functionality
- Survey type-dependent features (like logo hiding)
- Different display modes (settings page vs normal)
apps/web/modules/ui/components/file-upload-response/index.test.tsx
Outdated
Show resolved
Hide resolved
apps/web/modules/ui/components/editor/components/auto-link-plugin.test.tsx
Show resolved
Hide resolved
apps/web/modules/ui/components/data-table/components/data-table-header.test.tsx
Show resolved
Hide resolved
apps/web/modules/ui/components/confirm-delete-segment-modal/index.test.tsx
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looking good! Just need to fix the Rabbit issues!
|
What does this PR do?
Fixes #(issue)
How should this be tested?
Checklist
Required
pnpm build
console.logs
git pull origin main
Appreciated
Summary by CodeRabbit
Style
New Features
Tests