ConfirmModal: Allow button disable to be externally managed (#93446)

This commit is contained in:
Hugo Kiyodi Oshiro 2024-09-26 15:56:25 +02:00 committed by GitHub
parent 4b1d8eeef0
commit be8c8baf6f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 62 additions and 3 deletions

View File

@ -77,11 +77,15 @@ export const ConfirmContent = ({
}, [confirmPromptText, disabled]);
const onConfirmClick = async () => {
setIsDisabled(true);
if (disabled === undefined) {
setIsDisabled(true);
}
try {
await onConfirm();
} finally {
setIsDisabled(false);
if (disabled === undefined) {
setIsDisabled(false);
}
}
};

View File

@ -1,8 +1,11 @@
import { render, screen, waitFor } from '@testing-library/react';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useState } from 'react';
import { ConfirmModal } from './ConfirmModal';
jest.useFakeTimers();
describe('ConfirmModal', () => {
const mockOnConfirm = jest.fn();
@ -170,4 +173,56 @@ describe('ConfirmModal', () => {
return expect(screen.getByRole('button', { name: 'Please Confirm' })).toBeEnabled();
});
});
it('should disable the confirm button when disabled prop changes from false to true', async () => {
const TestComponent = () => {
const [disabled, setDisabled] = useState(false);
const handleConfirm = async () => {
act(() => {
setDisabled(true);
setTimeout(() => {
setDisabled(false);
}, 4000);
});
};
return (
<ConfirmModal
title="Some Title"
body="Some Body"
confirmText="Please Confirm"
isOpen={true}
onConfirm={handleConfirm}
onDismiss={() => {}}
onAlternative={() => {}}
disabled={disabled}
/>
);
};
render(<TestComponent />);
const confirmButton = screen.getByRole('button', { name: 'Please Confirm' });
expect(confirmButton).toBeEnabled();
fireEvent.click(confirmButton);
// Ensure React processes the state update and calls useEffect in ConfirmModal
await act(() => {
jest.advanceTimersByTime(0);
});
expect(confirmButton).toBeDisabled();
// Fast-forward time by 4 seconds
await act(() => {
jest.advanceTimersByTime(4000);
});
await waitFor(() => {
expect(confirmButton).toBeEnabled();
});
});
});