Which specific element should the userEvent.type(...) function target in order to work effectively with MUI's DesktopDatePicker TextField component?

Is there a way for me to input text into the TextField input within the MUI datepicker using react-testing-library's user-event? I've noticed that there is a mask applied to the input.

I attempted to use userEvent.type(inputEl, '1') and userEvent.keyboard('1'), but the input remained empty in both cases.

My current theory is that a rerender might be causing my updates to be replaced by the empty state of a higher order component, especially since the date format mask is being applied to the input.

The example in the documentation is working as intended, so it seems like my issue is specific to the MUI datepicker.

A simplified version of the component (and test) can be found in this sandbox.

Below is the rendered HTML snippet showing that I'm targeting the input element with a data-testid which does not seem to be working:

screen.getByTestId('date-selector-text-field').outerHTML:
<input
  aria-invalid="false"
  placeholder="dd / mm / yyyy"
  readonly=""
  type="text"
  aria-readonly="true"
  aria-label="Choose date"
  data-testid="date-selector-text-field"
  class="MuiOutlinedInput-input MuiInputBase-input css-1t8l2tu-MuiInputBase-input-MuiOutlinedInput-input"
  value=""
  aria-describedby="mui-1-helper-text"
  id="mui-1"
>

Answer №1

To ensure that the DatePicker is properly rendered for a Desktop in the test, I included the following code snippet. For more detailed information on this topic, you can refer to this link: https://github.com/mui/material-ui-pickers/issues/2073#issuecomment-671834179

beforeAll(() => {
    // Adding window.matchMedia
    // This is essential for the date picker to display in desktop mode.
    // Without this, the mobile mode may be displayed, resulting in unexpected behavior.
    Object.defineProperty(window, "matchMedia", {
      writable: true,
      value: (query: any) => ({
        media: query,
        // This is the media query used by @material-ui/pickers to determine if a device is a desktop
        matches: query === "(pointer: fine)",
        onchange: () => null,
        addEventListener: () => null,
        removeEventListener: () => null,
        addListener: () => null,
        removeListener: () => null,
        dispatchEvent: () => false,
      }),
    });
  });
  afterAll(() => {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    delete window.matchMedia;
  });

If the Datepicker already has a value and you are using userEvent.type(), remember to include an await userEvent.clear() before await userEvent.type(). This clearing step is necessary as it simulates real user interaction, and typing is not possible if a value is already present (as in my test case).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...

Add the scss file to the vuejs component npm package only if certain conditions specified in the project are met

Creating css/scss themes for my Vue Components Npm package has been a focus of mine lately. This particular package is local and currently being tested using npm link. Both the Package and Project are utilizing webpack. index.js of Package import "./src ...

JavaScript: Collection of Pictures

I've recently begun my journey into HTML and JavaScript by working on a basic website that showcases four images using a for loop. However, upon viewing the website in a browser, I noticed that only the names of the images are displayed, not the actua ...

Implementing a hamburger menu and social media sharing buttons on websites

Currently working on my personal website and delving into the world of Web Development, I have some inquiries for seasoned developers. My first query revolves around incorporating a hamburger menu onto my site for easy navigation to other pages. After att ...

The onchange event does not seem to be functioning as expected in a dropdown menu that was dynamically added from a separate

Is there a way to display a list of tables from a database in a dropdown menu and allow users to select a table name? When a user selects a table name, I would like to show all the data associated with that table. The HTML file structure is as follows: & ...

Removing items from a todo list in JSX without relying on props or state

I am facing a challenge with utilizing a function to delete an item from an array when clicking the delete button. I am seeking a solution without relying on props or state. Could someone please point out where I may be making a mistake? The item appears ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...

Clicking to close tabs

I am currently working on implementing a tab functionality on my website and I want these tabs to be responsive. Here is the code snippet I have been using: function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.ge ...

Using AJAX to invoke a REST service endpoint

I'm currently implementing a REST service call using AJAX. $(document).ready(function () { var xmml = getXmlLoginRequest(); var wsdlURL = getWSDL('search'); $.ajax({ type: "POST", url: wsdlURL ...

Alter the color of Material UI Raised Button when it is hovered over

I am trying to change the background color of a raised button on hover in Material UI. I attempted the following, but it did not work. Is there a way to modify the background color in Material UI for a raised button? Example.JS <RaisedButton ...

The compatibility issue between Bootstrap4 Navbar and "jQuery.BgSwitcher" is causing functionality limitations on mobile devices

Currently, I am utilizing Bootswatch4 within Bootstrap4 and have a requirement for a div with backgrounds that change or fade. After some research, I stumbled upon a JavaScript solution that aligns closely with my needs at: https://github.com/rewish/jquery ...

Utilizing AJAX with FullCalendar to seamlessly insert Bootstrap modal inputs into an SQL table

I've been struggling to implement user input from a modal into my phpMyAdmin database. Any assistance would be highly appreciated. 1) Triggering a modal with the select callback: select: function(start, end, allDay) { $('#myModal') ...

Inconsistencies in date formatting between Javascript and PHP yield varying results

While working with PHP, I noticed this: echo date("Y/m/d",786668400); The output is 1994/12/06 However, when I tried the same thing in JavaScript: console.log(new Date(786668400*1000).getDate() + "." + (new Date(786668400*1000).getMonth() + ...

Performing a JavaScript AJAX request to send a complex object containing an array of other complex objects within it

My issue arises from encountering an empty array of objects at the backend. To illustrate, I have established two classes at the backend... public class ScoreModel { public string Subject { get; set; } public float Score { get; set; } ...

Tips for revealing the pin after entering it into the text box

Is there a way to display the address inputted into 4 textboxes (with pin changing after onchange) on a Google map embedded on my website? I want to have 4 separate input fields for zip code, city, street, and house number. If all four boxes are filled out ...

Unable to access the "target" property while transferring a value from child to parent component

Within my project, the student component is considered a child component of the main app component. Inside the template of the student component, there is an input element defined like so: <input type='text' #inputbox (keyup)='onkeyUp(i ...

Get the data in string format and save it as a CSV file

I've coded a script that transforms a JSON object into comma-separated values using the ConvertToCSV function. Now I'm wondering how to save the variable csvData as a downloadable CSV file? The code is already wrapped inside a function triggered ...

Tips for getting information from firestore by implementing a where clause specific to a field within an object?

In my React Native project, I am utilizing Firebase Firestore as the backend database. I have successfully retrieved data from the database using the following code: unsubscribe = firebase.firestore().collection('messages').where('user&apos ...

Tips on implementing Piwik JavaScript code within app.js on Express

I am trying to implement Piwik tracking on my Express website using JavaScript code. I placed the code in my app.js file but encountered an error. Here is the JavaScript code snippet: <script type="text/javascript"> var _paq = _paq || []; ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...