Skip to content
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

[material-ui] Make tests compatible with React 19 #43155

Merged
merged 5 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages-internal/test-utils/src/createRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from '@testing-library/react/pure';
import { userEvent } from '@testing-library/user-event';
import { useFakeTimers } from 'sinon';
import reactMajor from './reactMajor';

interface Interaction {
id: number;
Expand Down Expand Up @@ -568,7 +569,7 @@ export function createRenderer(globalOptions: CreateRendererOptions = {}): Rende
wrapper: InnerWrapper = React.Fragment,
} = options;

const usesLegacyRoot = !React.version.startsWith('18');
const usesLegacyRoot = reactMajor < 18;
const Mode = strict && (strictEffects || usesLegacyRoot) ? React.StrictMode : React.Fragment;
return function Wrapper({ children }: { children?: React.ReactNode }) {
return (
Expand Down
4 changes: 2 additions & 2 deletions packages-internal/test-utils/src/fireDiscreteEvent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { configure, fireEvent, getConfig } from '@testing-library/react';
import reactMajor from './reactMajor';

const noWrapper = (callback: () => void) => callback();

Expand All @@ -8,7 +8,7 @@ const noWrapper = (callback: () => void) => callback();
* @returns {void}
*/
function withMissingActWarningsIgnored(callback: () => void) {
if (React.version.startsWith('18')) {
if (reactMajor >= 18) {
callback();
return;
}
Expand Down
3 changes: 3 additions & 0 deletions packages-internal/test-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ export {} from './initMatchers';
export * as fireDiscreteEvent from './fireDiscreteEvent';
export * as userEvent from './userEvent';
export { default as flushMicrotasks } from './flushMicrotasks';
export { default as reactMajor } from './reactMajor';
aarongarciah marked this conversation as resolved.
Show resolved Hide resolved

/**
* Set to true if console logs during [lifecycles that are invoked twice in `React.StrictMode`](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects) are suppressed.
* Useful for asserting on `console.warn` or `console.error` via `toErrorDev()`.
* TODO: Refactor to use reactMajor when fixing the React 17 cron test.
aarongarciah marked this conversation as resolved.
Show resolved Hide resolved
* https://github.com/mui/material-ui/issues/43153
*/
export const strictModeDoubleLoggingSuppressed = React.version.startsWith('17');
3 changes: 3 additions & 0 deletions packages-internal/test-utils/src/reactMajor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import * as React from 'react';

export default Number(React.version.split('.')[0]);
6 changes: 3 additions & 3 deletions packages-internal/test-utils/src/userEvent.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { click, mouseDown, mouseUp, keyDown, keyUp } from './fireDiscreteEvent';
import { act, fireEvent } from './createRenderer';
import reactMajor from './reactMajor';

export function touch(target: Element): void {
fireEvent.touchStart(target);
Expand All @@ -11,7 +11,7 @@ export const mousePress: (...args: Parameters<(typeof fireEvent)['mouseUp']>) =>
target,
options,
) => {
if (React.version.startsWith('18')) {
if (reactMajor >= 18) {
fireEvent.mouseDown(target, options);
fireEvent.mouseUp(target, options);
fireEvent.click(target, options);
Expand All @@ -24,7 +24,7 @@ export const mousePress: (...args: Parameters<(typeof fireEvent)['mouseUp']>) =>
};

export function keyPress(target: Element, options: { key: string; [key: string]: any }): void {
if (React.version.startsWith('18')) {
if (reactMajor >= 18) {
fireEvent.keyDown(target, options);
fireEvent.keyUp(target, options);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ describe('<NumberInput />', () => {
}}
/>,
);
}).toErrorDev('Warning: Unknown event handler property `onInputChange`. It will be ignored.');
}).toErrorDev('Unknown event handler property `onInputChange`. It will be ignored.');
});

it('should fire on keyboard input in the textbox instead of onChange', async () => {
Expand Down
58 changes: 38 additions & 20 deletions packages/mui-base/src/useAutocomplete/useAutocomplete.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import * as React from 'react';
import { expect } from 'chai';
import { createRenderer, screen, ErrorBoundary, act, fireEvent } from '@mui/internal-test-utils';
import {
createRenderer,
screen,
ErrorBoundary,
act,
fireEvent,
reactMajor,
} from '@mui/internal-test-utils';
import { spy } from 'sinon';
import { useAutocomplete, createFilterOptions } from '@mui/base/useAutocomplete';

Expand Down Expand Up @@ -276,28 +283,39 @@ describe('useAutocomplete', () => {
);
}

const muiErrorMessage = 'MUI: Unable to find the input element.';
const aboveErrorUlElementMessage = 'The above error occurred in the <ul> component';
const aboveErrorTestComponentMessage = 'The above error occurred in the <Test> component';
const node16ErrorMessage =
"Error: Uncaught [TypeError: Cannot read properties of null (reading 'removeAttribute')]";
const olderNodeErrorMessage =
"Error: Uncaught [TypeError: Cannot read property 'removeAttribute' of null]";
"TypeError: Cannot read properties of null (reading 'removeAttribute')";
const olderNodeErrorMessage = "TypeError: Cannot read property 'removeAttribute' of null";

const nodeVersion = Number(process.versions.node.split('.')[0]);
const errorMessage = nodeVersion >= 16 ? node16ErrorMessage : olderNodeErrorMessage;

const devErrorMessages = [
errorMessage,
'MUI: Unable to find the input element.',
errorMessage,
// strict effects runs effects twice
React.version.startsWith('18') && 'MUI: Unable to find the input element.',
React.version.startsWith('18') && errorMessage,
'The above error occurred in the <ul> component',
React.version.startsWith('16') && 'The above error occurred in the <ul> component',
'The above error occurred in the <Test> component',
// strict effects runs effects twice
React.version.startsWith('18') && 'The above error occurred in the <Test> component',
React.version.startsWith('16') && 'The above error occurred in the <Test> component',
];
const nodeErrorMessage = nodeVersion >= 16 ? node16ErrorMessage : olderNodeErrorMessage;

const defaultErrorMessages = [muiErrorMessage, nodeErrorMessage, nodeErrorMessage];

const errorMessagesByReactMajor = {
17: [
nodeErrorMessage,
muiErrorMessage,
nodeErrorMessage,
aboveErrorUlElementMessage,
aboveErrorTestComponentMessage,
],
18: [
nodeErrorMessage,
muiErrorMessage,
nodeErrorMessage,
muiErrorMessage,
nodeErrorMessage,
aboveErrorUlElementMessage,
aboveErrorTestComponentMessage,
aboveErrorTestComponentMessage,
],
};

const devErrorMessages = errorMessagesByReactMajor[reactMajor] || defaultErrorMessages;

expect(() => {
render(
Expand Down
51 changes: 29 additions & 22 deletions packages/mui-joy/src/Autocomplete/Autocomplete.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
act,
fireEvent,
strictModeDoubleLoggingSuppressed,
reactMajor,
} from '@mui/internal-test-utils';
import Autocomplete, {
autocompleteClasses as classes,
Expand Down Expand Up @@ -1209,19 +1210,19 @@ describe('Joy <Autocomplete />', () => {
const value = 'not a good value';
const options = ['first option', 'second option'];

const errorMessage = 'None of the options match with `"not a good value"`';

let expectedOccurrences = 4;

if (reactMajor === 18) {
expectedOccurrences = 6;
} else if (reactMajor === 17) {
expectedOccurrences = 2;
}

expect(() => {
render(<Autocomplete value={value} options={options} />);
}).toWarnDev([
'None of the options match with `"not a good value"`',
!strictModeDoubleLoggingSuppressed && 'None of the options match with `"not a good value"`',
'None of the options match with `"not a good value"`',
!strictModeDoubleLoggingSuppressed && 'None of the options match with `"not a good value"`',
// React 18 Strict Effects run mount effects twice which lead to a cascading update
React.version.startsWith('18') && 'None of the options match with `"not a good value"`',
React.version.startsWith('18') &&
!strictModeDoubleLoggingSuppressed &&
'None of the options match with `"not a good value"`',
]);
}).toWarnDev(Array(expectedOccurrences).fill(errorMessage));
});

it('warn if groups options are not sorted', () => {
Expand Down Expand Up @@ -1930,9 +1931,11 @@ describe('Joy <Autocomplete />', () => {

await user.click(screen.getByText('Reset'));

expect(handleInputChange.callCount).to.equal(4);
expect(handleInputChange.args[3][1]).to.equal(options[1].name);
expect(handleInputChange.args[3][2]).to.equal('reset');
const expectedCallCount = reactMajor === 18 ? 4 : 2;

expect(handleInputChange.callCount).to.equal(expectedCallCount);
expect(handleInputChange.args[expectedCallCount - 1][1]).to.equal(options[1].name);
expect(handleInputChange.args[expectedCallCount - 1][2]).to.equal('reset');
});

it('provides a reason on clear', async () => {
Expand Down Expand Up @@ -2186,10 +2189,10 @@ describe('Joy <Autocomplete />', () => {
);
expect(handleHighlightChange.callCount).to.equal(
// FIXME: highlighted index implementation should be implemented using React not the DOM.
React.version.startsWith('18') ? 2 : 1,
reactMajor >= 18 ? 2 : 1,
);
expect(handleHighlightChange.args[0]).to.deep.equal([undefined, options[0], 'auto']);
if (React.version.startsWith('18')) {
if (reactMajor >= 18) {
expect(handleHighlightChange.args[1]).to.deep.equal([undefined, options[0], 'auto']);
}
});
Expand All @@ -2206,9 +2209,9 @@ describe('Joy <Autocomplete />', () => {

expect(handleHighlightChange.callCount).to.equal(
// FIXME: highlighted index implementation should be implemented using React not the DOM.
React.version.startsWith('18') ? 4 : 3,
reactMajor >= 18 ? 4 : 3,
);
if (React.version.startsWith('18')) {
if (reactMajor >= 18) {
expect(handleHighlightChange.args[2][0]).to.equal(undefined);
expect(handleHighlightChange.args[2][1]).to.equal(null);
expect(handleHighlightChange.args[2][2]).to.equal('auto');
Expand All @@ -2220,7 +2223,7 @@ describe('Joy <Autocomplete />', () => {
fireEvent.keyDown(textbox, { key: 'ArrowDown' });
expect(handleHighlightChange.callCount).to.equal(
// FIXME: highlighted index implementation should be implemented using React not the DOM.
React.version.startsWith('18') ? 5 : 4,
reactMajor >= 18 ? 5 : 4,
);
expect(handleHighlightChange.lastCall.args[0]).not.to.equal(undefined);
expect(handleHighlightChange.lastCall.args[1]).to.equal(options[1]);
Expand All @@ -2237,9 +2240,9 @@ describe('Joy <Autocomplete />', () => {
fireEvent.mouseMove(firstOption);
expect(handleHighlightChange.callCount).to.equal(
// FIXME: highlighted index implementation should be implemented using React not the DOM.
React.version.startsWith('18') ? 4 : 3,
reactMajor >= 18 ? 4 : 3,
);
if (React.version.startsWith('18')) {
if (reactMajor >= 18) {
expect(handleHighlightChange.args[2][0]).to.equal(undefined);
expect(handleHighlightChange.args[2][1]).to.equal(null);
expect(handleHighlightChange.args[2][2]).to.equal('auto');
Expand Down Expand Up @@ -2284,7 +2287,11 @@ describe('Joy <Autocomplete />', () => {
checkHighlightIs(getByRole('listbox'), 'one');
setProps({ options: ['four', 'five'] });
checkHighlightIs(getByRole('listbox'), 'four');
expect(handleHighlightChange).to.deep.equal([null, 'one', 'four']);

const expectedCallHistory =
reactMajor >= 19 ? [null, 'one', 'one', 'four'] : [null, 'one', 'four'];

expect(handleHighlightChange).to.deep.equal(expectedCallHistory);
});
});

Expand Down
4 changes: 2 additions & 2 deletions packages/mui-lab/src/Masonry/Masonry.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { createRenderer } from '@mui/internal-test-utils';
import { createRenderer, reactMajor } from '@mui/internal-test-utils';
import { expect } from 'chai';
import { createTheme } from '@mui/material/styles';
import defaultTheme from '@mui/material/styles/defaultTheme';
Expand Down Expand Up @@ -100,7 +100,7 @@ describe('<Masonry />', () => {
});

it('should throw console error when children are empty', function test() {
if (!/jsdom/.test(window.navigator.userAgent)) {
if (!/jsdom/.test(window.navigator.userAgent) || reactMajor >= 19) {
this.skip();
}
expect(() => render(<Masonry columns={3} spacing={1} />)).toErrorDev(
Expand Down
9 changes: 7 additions & 2 deletions packages/mui-material/src/Accordion/Accordion.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react';
import PropTypes from 'prop-types';
import { expect } from 'chai';
import { spy } from 'sinon';
import { createRenderer, fireEvent } from '@mui/internal-test-utils';
import { createRenderer, fireEvent, reactMajor } from '@mui/internal-test-utils';
import Accordion, { accordionClasses as classes } from '@mui/material/Accordion';
import Paper from '@mui/material/Paper';
import AccordionSummary from '@mui/material/AccordionSummary';
Expand Down Expand Up @@ -158,7 +158,12 @@ describe('<Accordion />', () => {

describe('prop: children', () => {
describe('first child', () => {
beforeEach(() => {
beforeEach(function beforeEachCallback() {
if (reactMajor >= 19) {
// React 19 removed prop types support
this.skip();
}

PropTypes.resetWarningCache();
});

Expand Down
Loading