Mui DatePicker button not available on first render in tests

Viewed 537

The new Material UI DatePicker has a renderInput prop that gets a function that renders a text field. Works well enough, except that this function is rendered twice, and on first render it only receives some of the props it needs.

When rendered with React Testing Library, only the first render happens. Notably, the endAdornment is not present. So it's impossible to getByRole('button') and click the button to open the picker modal.

I've tried various permutations of waitFor() and rerender() but can't seem to get the button to show up.

Here's a code sandbox that shows the two versions of the renderInput params being logged out. (I've also got a test in there to look for the button, but unfortunately I'm also doing something wrong with the test and it's not running.)

Any suggestions?

1 Answers

It is because Mui’s DatePicker render mobile view by default.

Below would fix it:

beforeEach(() => {
  // add window.matchMedia
  // this is necessary for the date picker to be rendered in     desktop mode.
  // if this is not provided, the mobile mode is rendered, which might lead to unexpected behavior
  Object.defineProperty(window, 'matchMedia', {
    writable: true,
    value: (query: string): MediaQueryList => ({
      media: query,
      // this is the media query that @material-ui/pickers uses to determine if a device is a desktop device
      matches: query === '(pointer: fine)',
      onchange: () => {},
      addEventListener: () => {},
      removeEventListener: () => {},
      addListener: () => {},
      removeListener: () => {},
      dispatchEvent: () => false,
    }),
  });
});

afterEach(() => {
  delete window.matchMedia;
});

For more details: github issue

Related