forked from OpenStackweb/summit-admin
-
Notifications
You must be signed in to change notification settings - Fork 4
fix: replace item popup with shared item popup, adjust props and actions #1034
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
Open
tomrndom
wants to merge
4
commits into
master
Choose a base branch
from
fix/sponsor-global-manage-item-popup
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
ed89f0e
fix: replace item popup with shared item popup, adjust props, change …
tomrndom 8779af4
fix: rollback changes on saveSponsorFormItem, add tests on image delete
tomrndom af2b6eb
fix: add unit test cases for saving guard
tomrndom 2c031d2
fix: change test to check double click save button
tomrndom File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
326 changes: 326 additions & 0 deletions
326
src/pages/sponsors-global/form-templates/__tests__/sponsor-inventory-popup.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,326 @@ | ||
| import React from "react"; | ||
| import { render, screen, waitFor, fireEvent } from "@testing-library/react"; | ||
| import userEvent from "@testing-library/user-event"; | ||
| import "@testing-library/jest-dom"; | ||
| import SponsorItemDialog from "../sponsor-inventory-popup"; | ||
|
|
||
| jest.mock("i18n-react/dist/i18n-react", () => ({ | ||
| translate: jest.fn((key) => key) | ||
| })); | ||
|
|
||
| jest.mock("../../../../hooks/useScrollToError", () => jest.fn()); | ||
|
|
||
| jest.mock( | ||
| "openstack-uicore-foundation/lib/components/mui/formik-inputs/upload", | ||
| () => | ||
| function MockMuiFormikUpload({ name, onDelete }) { | ||
| return ( | ||
| <div data-testid={`upload-${name}`}> | ||
| <button type="button" onClick={() => onDelete(5)}> | ||
| delete-persisted-image | ||
| </button> | ||
| <button type="button" onClick={() => onDelete(undefined)}> | ||
| delete-unsaved-image | ||
| </button> | ||
| </div> | ||
| ); | ||
| } | ||
| ); | ||
|
|
||
| jest.mock( | ||
| "openstack-uicore-foundation/lib/components/mui/formik-inputs/additional-input-list", | ||
| () => | ||
| function MockAdditionalInputList({ name }) { | ||
| return <div data-testid={`meta-fields-${name}`} />; | ||
| } | ||
| ); | ||
|
|
||
| jest.mock( | ||
| "../../../../components/mui/formik-inputs/item-price-tiers", | ||
| () => | ||
| function MockItemPriceTiers() { | ||
| return <div data-testid="price-tiers" />; | ||
| } | ||
| ); | ||
|
|
||
| jest.mock( | ||
| "../../../../components/inputs/formik-text-editor", | ||
| () => | ||
| function MockFormikTextEditor({ name }) { | ||
| return <textarea data-testid={`editor-${name}`} name={name} readOnly />; | ||
| } | ||
| ); | ||
|
|
||
| const BASE_ENTITY = { | ||
| id: 0, | ||
| code: "", | ||
| name: "", | ||
| description: "", | ||
| early_bird_rate: "", | ||
| standard_rate: "", | ||
| onsite_rate: "", | ||
| quantity_limit_per_show: "", | ||
| quantity_limit_per_sponsor: "", | ||
| meta_fields: [], | ||
| images: [] | ||
| }; | ||
|
|
||
| const fillRequiredTextFields = async (user) => { | ||
| await user.type(document.querySelector("input[name=\"code\"]"), "CODE-1"); | ||
| await user.type(document.querySelector("input[name=\"name\"]"), "Item 1"); | ||
| }; | ||
|
|
||
| const submit = async (user) => { | ||
| await user.click( | ||
| screen.getByRole("button", { name: "edit_inventory_item.save_changes" }) | ||
| ); | ||
| }; | ||
|
|
||
| describe("SponsorItemDialog", () => { | ||
| let onSave; | ||
| let onClose; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| onSave = jest.fn(() => Promise.resolve()); | ||
| onClose = jest.fn(); | ||
| }); | ||
|
|
||
| it("titles itself by whether the entity has an id", () => { | ||
| const { rerender } = render( | ||
| <SponsorItemDialog | ||
| entity={BASE_ENTITY} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| /> | ||
| ); | ||
| expect( | ||
| screen.getByText("edit_inventory_item.new_item") | ||
| ).toBeInTheDocument(); | ||
|
|
||
| rerender( | ||
| <SponsorItemDialog | ||
| entity={{ ...BASE_ENTITY, id: 42 }} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| /> | ||
| ); | ||
| expect( | ||
| screen.getByText("edit_inventory_item.edit_item") | ||
| ).toBeInTheDocument(); | ||
| }); | ||
|
|
||
| it("blocks save when code/name are empty", async () => { | ||
| const user = userEvent.setup(); | ||
| render( | ||
| <SponsorItemDialog | ||
| entity={BASE_ENTITY} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| /> | ||
| ); | ||
|
|
||
| await submit(user); | ||
|
|
||
| expect(onSave).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| describe("default_quantity requirement", () => { | ||
| it("is optional by default: saves with no value and shows no required marker", async () => { | ||
| const user = userEvent.setup(); | ||
| render( | ||
| <SponsorItemDialog | ||
| entity={BASE_ENTITY} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| /> | ||
| ); | ||
|
|
||
| expect( | ||
| screen.queryByText("edit_inventory_item.default_quantity *") | ||
| ).not.toBeInTheDocument(); | ||
|
|
||
| await fillRequiredTextFields(user); | ||
| await submit(user); | ||
|
|
||
| await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); | ||
| expect(onClose).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("blocks save, shows the error and the required marker when required and empty", async () => { | ||
| const user = userEvent.setup(); | ||
| render( | ||
| <SponsorItemDialog | ||
| entity={{ ...BASE_ENTITY, default_quantity: undefined }} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| requireDefaultQuantity | ||
| /> | ||
| ); | ||
|
|
||
| expect( | ||
| screen.getByText("edit_inventory_item.default_quantity *") | ||
| ).toBeInTheDocument(); | ||
|
|
||
| await fillRequiredTextFields(user); | ||
| await submit(user); | ||
|
|
||
| expect(onSave).not.toHaveBeenCalled(); | ||
| expect( | ||
| await screen.findByText("validation.required") | ||
| ).toBeInTheDocument(); | ||
| }); | ||
|
|
||
| it("allows save once a value is provided when required", async () => { | ||
| const user = userEvent.setup(); | ||
| render( | ||
| <SponsorItemDialog | ||
| entity={{ ...BASE_ENTITY, default_quantity: "" }} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| requireDefaultQuantity | ||
| /> | ||
| ); | ||
|
|
||
| await fillRequiredTextFields(user); | ||
| await user.type( | ||
| document.querySelector("input[name=\"default_quantity\"]"), | ||
| "5" | ||
| ); | ||
| await submit(user); | ||
|
|
||
| await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); | ||
| expect(onSave.mock.calls[0][0]).toEqual( | ||
| expect.objectContaining({ default_quantity: 5 }) | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe("image deletion", () => { | ||
| it("calls onImageDeleted only for a persisted image (has an id)", async () => { | ||
| const user = userEvent.setup(); | ||
| const onImageDeleted = jest.fn(); | ||
| render( | ||
| <SponsorItemDialog | ||
| entity={{ ...BASE_ENTITY, id: 42 }} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| onImageDeleted={onImageDeleted} | ||
| /> | ||
| ); | ||
|
|
||
| await user.click(screen.getByText("delete-unsaved-image")); | ||
| expect(onImageDeleted).not.toHaveBeenCalled(); | ||
|
|
||
| await user.click(screen.getByText("delete-persisted-image")); | ||
| expect(onImageDeleted).toHaveBeenCalledWith(5); | ||
| expect(onImageDeleted).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("does nothing when onImageDeleted is not provided", async () => { | ||
| const user = userEvent.setup(); | ||
| render( | ||
| <SponsorItemDialog | ||
| entity={{ ...BASE_ENTITY, id: 42 }} | ||
| onSave={onSave} | ||
| onClose={onClose} | ||
| /> | ||
| ); | ||
|
|
||
| await expect( | ||
| user.click(screen.getByText("delete-persisted-image")) | ||
| ).resolves.not.toThrow(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("save guard", () => { | ||
| const renderPending = (save) => | ||
| render( | ||
| <SponsorItemDialog | ||
| entity={BASE_ENTITY} | ||
| onSave={save} | ||
| onClose={onClose} | ||
| /> | ||
| ); | ||
|
|
||
| it("disables the save and close buttons while a save is in flight, and closes on success", async () => { | ||
| const user = userEvent.setup(); | ||
| let resolveSave; | ||
| const pendingSave = jest.fn( | ||
| () => | ||
| new Promise((resolve) => { | ||
| resolveSave = resolve; | ||
| }) | ||
| ); | ||
| renderPending(pendingSave); | ||
|
|
||
| await fillRequiredTextFields(user); | ||
| const saveButton = screen.getByRole("button", { | ||
| name: "edit_inventory_item.save_changes" | ||
| }); | ||
| await user.click(saveButton); | ||
|
|
||
| await waitFor(() => expect(saveButton).toBeDisabled()); | ||
| expect(screen.getByTestId("CloseIcon").closest("button")).toBeDisabled(); | ||
|
|
||
| resolveSave(); | ||
|
|
||
| await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1)); | ||
| expect(pendingSave).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("does not call onSave twice when the save button is double-clicked before isSaving commits", async () => { | ||
| let resolveSave; | ||
| const pendingSave = jest.fn( | ||
| () => | ||
| new Promise((resolve) => { | ||
| resolveSave = resolve; | ||
| }) | ||
| ); | ||
| renderPending(pendingSave); | ||
|
|
||
| fireEvent.change(document.querySelector("input[name=\"code\"]"), { | ||
| target: { value: "CODE-1" } | ||
| }); | ||
| fireEvent.change(document.querySelector("input[name=\"name\"]"), { | ||
| target: { value: "Item 1" } | ||
| }); | ||
|
|
||
| const saveButton = screen.getByRole("button", { | ||
| name: "edit_inventory_item.save_changes" | ||
| }); | ||
|
|
||
| // Fired back-to-back with no await in between, so both clicks reach | ||
| // formik's validation before React commits the isSaving state update | ||
| // that disables the button - this is the actual race `if (isSaving) | ||
| // return` in handleOnSave guards against (validation is async, so a | ||
| // real fast double-click can land before the first render commits). | ||
| fireEvent.click(saveButton); | ||
| fireEvent.click(saveButton); | ||
|
|
||
| await waitFor(() => expect(pendingSave).toHaveBeenCalled()); | ||
| resolveSave(); | ||
|
|
||
| await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1)); | ||
| expect(pendingSave).toHaveBeenCalledTimes(1); | ||
| }); | ||
|
|
||
| it("keeps the dialog open and re-enables the form when onSave rejects", async () => { | ||
| const user = userEvent.setup(); | ||
| const rejectingSave = jest.fn(() => | ||
| Promise.reject(new Error("save failed")) | ||
| ); | ||
| renderPending(rejectingSave); | ||
|
|
||
| await fillRequiredTextFields(user); | ||
| const saveButton = screen.getByRole("button", { | ||
| name: "edit_inventory_item.save_changes" | ||
| }); | ||
| await user.click(saveButton); | ||
|
|
||
| await waitFor(() => expect(rejectingSave).toHaveBeenCalled()); | ||
| await waitFor(() => expect(saveButton).not.toBeDisabled()); | ||
| expect(onClose).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🌐 Web query:
For React 16.13.1, does a disabled native button invoke its React onClick handler when Testing Library calls fireEvent.click on it?💡 Result:
For React 16.13.1, a disabled native button does not typically invoke its React onClick handler when fireEvent.click is called via Testing Library [1][2][3]. When a native element has the disabled attribute, it is functionally disabled according to HTML specifications [4][1]. In standard browser environments, disabled form controls are intended to prevent user interaction, including click events [1]. However, there is an important nuance regarding how testing tools interact with the DOM. Testing Library's fireEvent.click is a low-level utility that triggers a DOM event directly on the specified element [5]. While the library and the underlying JSDOM environment have evolved to respect the disabled state for many elements, historical issues have existed where test utilities might bypass these browser-level restrictions [1]. If you find that your onClick handler is still being called in a test, it is usually because: 1. The element being clicked is not a native (e.g., a
@testing-library/jest-dom, rather than relying solely on checking if the onClick handler was called [2]. Example of recommended testing approach: import { render, screen, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; // Provides toBeDisabled test('does not call onClick when button is disabled', => { const handleClick = jest.fn; render(Citations:
🏁 Script executed:
Repository: fntechgit/summit-admin
Length of output: 50379
🏁 Script executed:
Repository: fntechgit/summit-admin
Length of output: 10060
🏁 Script executed:
Repository: fntechgit/summit-admin
Length of output: 5329
🌐 Web query:
React 16.14.0 disabled button dispatchEvent fireEvent.click onClick shouldPreventMouseEvent source💡 Result:
In React, the behavior where
onClickhandlers are not triggered on disabled buttons is a feature of React's synthetic event system designed to align with the HTML specification [1][2][3]. React implements an internal function often referred to in its codebase asshouldPreventMouseEvent[4][5][6]. This mechanism checks whether a target element or its ancestors are disabled (specifically for interactive elements like<button>,<input>, etc.) before deciding whether to dispatch synthetic events such asonClickoronMouseEnter[4][5][6]. Regarding the interaction between manual event dispatching and disabled states: 1. Synthetic vs. Native Events: React'sonClickis a synthetic event that React manages. When you usefireEvent.click()(from Testing Library) or manually callelement.dispatchEvent()in a test environment, you are often bypassing React's internal "should-prevent" logic if you are not using React's event simulation methods properly [7][8]. 2. Testing Libraries and JSDOM:fireEvent.click()simply dispatches a native DOM event [9]. In many test environments (like JSDOM),dispatchEventdoes not automatically respect thedisabledattribute in the same way a real browser does, or it may behave inconsistently because JSDOM's implementation of event bubbling and disabled-state handling can differ from actual browser engines [10][8]. This is why tests might show events firing on disabled buttons even though the React application itself would correctly suppress them in a browser [11][8]. 3. Workarounds: If you are encountering issues where events fire on disabled elements during testing, the standard advice is to rely onuserEvent.click()from@testing-library/user-eventinstead offireEvent.click().userEventsimulates a full sequence of events (e.g.,mousedown,mouseup,click) and is designed to respect the disabled state of elements, better mimicking real user interaction and React's internal handling [9]. In summary, React intentionally preventsonClickfrom firing on disabled buttons via internal suppression logic [4][5]. If your tests indicate otherwise, it is likely becausefireEventordispatchEventis interacting with the DOM at a lower level than React's synthetic system, or the test environment (JSDOM) is not strictly adhering to the disabled-element event handling spec [10][8].Citations:
🏁 Script executed:
Repository: fntechgit/summit-admin
Length of output: 10317
🌐 Web query:
site:github.com/facebook/react v16.14.0 shouldPreventMouseEvent disabled onClick DOMPluginEventSystem💡 Result:
In React,
shouldPreventMouseEventis an internal utility function historically located withinSimpleEventPlugin[1][2]. It is responsible for determining whether mouse events (likeonClick,onMouseEnter, etc.) should be blocked when triggered on disabled interactive elements (such as<button>,<input>, etc.) [1][2][3]. When a component is marked asdisabled, React's synthetic event system uses this function to prevent these events from firing, ensuring that disabled interactive elements do not execute their assigned handlers [1][4][2]. Key technical points regarding this mechanism: 1. Purpose: The function ensures that disabled elements in the DOM do not trigger React event listeners, maintaining consistent behavior with native browser expectations where disabled elements should be non-interactive [1][2]. 2. Mechanism:shouldPreventMouseEventchecks thedisabledproperty of the target element (or its parent in the fiber tree) [1]. If the element is disabled, it evaluates whether the specific event type should be suppressed for that interactive component type [1][3]. 3. Evolution: The implementation of this logic has evolved over time. Early versions of React handled this differently, but it was eventually moved intoSimpleEventPluginto centralize the filtering of mouse events for disabled elements [2]. 4. Limitations and Known Issues: Over the years, various issues have been reported where specific events (likeonContextMenuoronMouseEnter) were not correctly captured by this filter in certain browser environments or versions [5][3]. These are typically resolved by updating the list of event types processed byshouldPreventMouseEvent[5][3]. 5. Version context: In React v16.14.0, this system is part of the mature event plugin architecture [6]. Issues related to events firing on disabled elements in this version are often tied to how specific browser-native events bubble or are simulated in test environments, rather than a failure of theshouldPreventMouseEventutility itself [6]. Direct manipulation of the DOM (e.g., usingrefsto manually enable a button while React still thinks it is disabled) can cause the event system to become out of sync, leading to handlers failing to fire because the synthetic event system is still applying theshouldPreventMouseEventcheck based on the component's internal state, not the manual DOM change [4].Citations:
Exercise the re-entrant save guard through form submission.
SponsorItemDialogattachesformik.handleSubmitto the form, not to the button.fireEvent.click(saveButton)dispatches a low-level click and does not run the button’s submit action, so it cannot reachif (isSaving) return. Submit the form directly after the first save starts, then assert thatonSavehas one call.🤖 Prompt for AI Agents