Skip to content

Commit

Permalink
[fix] Fix Rating return NaN when using user event
Browse files Browse the repository at this point in the history
  • Loading branch information
NooBat committed Jan 18, 2025
1 parent c4f898d commit b7804d9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/mui-material/src/Rating/Rating.js
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,12 @@ const Rating = React.forwardRef(function Rating(inProps, ref) {
let newHover = roundValueToPrecision(max * percent + precision / 2, precision);
newHover = clamp(newHover, precision, max);

if (Number.isNaN(newHover)) {
// Workaround for test scenario using userEvent since jsdom defaults getBoundingClientRect to 0
// Fix https://github.com/mui/material-ui/issues/38828
newHover = -1;
}

setState((prev) =>
prev.hover === newHover && prev.focus === newHover
? prev
Expand Down
16 changes: 16 additions & 0 deletions packages/mui-material/src/Rating/Rating.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { stub, spy } from 'sinon';
import { act, createRenderer, fireEvent, screen } from '@mui/internal-test-utils';
import Rating, { ratingClasses as classes } from '@mui/material/Rating';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import userEvent from '@testing-library/user-event';
import describeConformance from '../../test/describeConformance';

describe('<Rating />', () => {
Expand Down Expand Up @@ -121,6 +122,21 @@ describe('<Rating />', () => {
expect(checked.value).to.equal('2');
});

it('should select the rating with user clicks', async () => {
const user = userEvent.setup();
const handleChange = spy();

const { container } = render(<Rating name="rating-test" onChange={handleChange} />);

await user.click(screen.getByLabelText('2 Stars'));

expect(handleChange.callCount).to.equal(1);
expect(handleChange.args[0][1]).to.equal(2);

const checked = container.querySelector('input[name="rating-test"]:checked');
expect(checked.value).to.equal('2');
});

it('should change the value to null', () => {
const handleChange = spy();
render(<Rating name="rating-test" onChange={handleChange} value={2} />);
Expand Down

0 comments on commit b7804d9

Please sign in to comment.