The efficiency of Testing Library findBy* queries is optimized when utilized alongside async/await functionality

After reviewing the documentation, it was noted that queries made using findBy return a Promise. Interestingly, utilizing these queries with Promise.prototype.catch() seems ineffective in comparison to pairing them with async/await + try...catch.

An instance where 'not found' is correctly logged can be seen below:

const { screen } = require('@testing-library/dom');

beforeAll(() => {
  document.body.innerHTML = `
    <header></header>
  `;
});

test('DOM', async () => {
  try {
    await screen.findByRole('aaaaa');
    console.log('found');
  } catch {
    console.log('not found');
  }
});

However, no logs are shown in this scenario:

test('DOM', () => {
  screen.findByRole('aaaaa')
    .then(() => {
      console.log('found');
    })
    .catch(() => {
      console.log('not found');
    });
});

Could there be an explanation for this difference in behavior?

Answer №1

Make sure to always return the Promise to signal your testing framework, such as Jest, to await the completion of the test. Otherwise, Jest won't be able to detect that this is an asynchronous test; using the async keyword will implicitly return a Promise.

const { screen } = require('@testing-library/dom');

test('DOM', () => {
  return screen.findByRole('aaaaa')
    .then(() => {
      console.log('found');
    })
    .catch(() => {
      console.log('not found');
    });
});

Answer №2

It's important to note that the examples provided are not actually equivalent. The code snippet screen.findByRole('aaaaa') does not exist within a Promise structure. By making the function asynchronous, it will be automatically wrapped in a Promise. Below is an improved version of the async/await implementation for your reference.

To handle cases where the function returns an error while also addressing the requirement of "throwing an error in a Promise...," I have made some modifications to the code.

// For illustration purposes only, fake implementations have been added
let screen={
  findByRole: () => new Promise((resolve, reject) => setTimeout(
    () => {reject(new Error('The error'))}, 2000
  ))
}

// Uncomment different scenarios below to test various conditions
// let screen={findByRole:() => new Error('The error')}
// let screen={findByRole:() => 5}

function test(desc, func)
{
  func()
}
/////

test('DOM', () => {
  new Promise(
    (resolve, reject) => {
      let result = screen.findByRole('aaaaa')
      result instanceof Error ? reject(result) : resolve(result)
    })
    .then(() => {
      console.log('Element found successfully');
    })
    .catch((e) => {
      console.error('Element not found and caught error: ' + e.message);
    });
});

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

Optimal method for retrieving data from asynchronous functions in JavaScript

Currently, I am using the twit library for nodejs which has async calls. In my code, I have created functions like the following: function getUserFromSearch(phrase) { T.get('search/tweets', { q: phrase+' lang:pt', count: 1 }, funct ...

It looks like everything is running smoothly, but it seems like the ReactDOM.render() method is missing in action

I'm currently diving into the world of React.js and eager to build my knowledge from the basics upwards. While delving into the documentation, I stumbled upon the utilization of ReactDOM.render(element, Document.getElementById("root")), whi ...

so many alerts to choose from aside from jsx/react

After some consideration, I believed I had devised an effective way to notify users when the array is empty and there's nothing to display. However, upon implementation, I realized my technique only works onFocus or page reload because I placed the fu ...

Extracting information from JSON using jQuery

this is a sample json object: { "box 1": [{ "difficulty_grade": "5a+" }, { "gym": "New_gym" }, { "route_author": "some author" },]} https://i.sstatic.net/UJodJ.png Here is the code snippet: variable groups contains JSON data as shown in the ...

Utilizing variable query operators solely in instances where they hold value

Imagine you are on a movie website where you can customize filters for the movies displayed to you. Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like: preferences: { yea ...

Vue component with a variable number of rows, each containing a variable number of input fields

I am currently working on creating a form that can have a variable number of steps. Users should be able to add an additional step by clicking a button. Each step will contain some input fields and buttons to dynamically create more input fields. For inst ...

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

Is there a way to prevent a web page from automatically refreshing using JavaScript?

I would like my webpage to automatically refresh at regular intervals. However, if a user remains inactive for more than 5 minutes, I want the refreshing to stop. There is an example of this on http://codepen.io/tetonhiker/pen/gLeRmw. Currently, the page ...

Is there a way to disable auto rotation on a website when accessed from a mobile phone?

My current solution involves the following code: @media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { html{ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(- ...

Adding new data to a Chart.js line graph in vue on form submission - A step-by-step guide

I'm struggling with dynamically updating my line chart with new data. I want the chart to refresh every time a user submits a form with new data. Currently, I can add new data to the datasets array in the data function of App.vue, but the chart doesn& ...

What is the best way to retrieve data from divs that are nested within another element using Javascript?

I am currently working on implementing a modal that will showcase specific information based on the event-card it originates from. Here is an HTML snippet showcasing an example event-card: <div class="event-card upcoming hackathon"> <d ...

Maximizing Particle Performance Using JavaScript

I am experimenting with creating particles in JavaScript for the first time, and I'm unsure if the code below is optimized. When I generate 100 particles on the screen, there isn't much of an FPS drop noticeable. However, when multiple clicks o ...

Using Node.js to import modules without the need for assignment

In my recent project, I decided to organize my express application by putting all of my routes in a separate file named routes.js: module.exports = function(server) { // Server represents the Express object server.get('/something', (req, res) ...

Using JavaScript regular expressions for email validation criteria

Hey there, I am struggling with Regular Expressions, especially when it comes to client side validation for a specific field. Can you please help me come up with a Regular Expression that would verify if an email address is valid based on these criteria: ...

What are the steps to incorporate swipe functionality into my component?

I've created a carousel using React-slideshow-image, but the issue is that it doesn't support swiping on mobile devices. I would like to implement swipe functionality myself, but I'm not sure how to go about it. Can anyone provide guidance ...

Tips for getting rid of Next.js' default loading indicator

While working on my project using Next.js, I've noticed that whenever I change the route, a default loading indicator appears in the corner of the screen. https://i.sstatic.net/FVWEU.gif Does anyone know how to remove this default loading indicator ...

Converting data from Node.js 6.10 from hexadecimal to base64 and then to UTF-8

I have a code snippet that generates "data" containing a JSON object. My goal is to extract the HEX-value from the Buffer in the data, and then decode it from HEX to BASE64 to UTF8 in order to convert it into a string. Here is the code snippet: console.l ...

I am encountering a horizontal scroll bar despite setting the width to 100%

I am just starting out as a beginner in web development. I decided to create a webpage to practice my HTML and CSS skills. However, when I set the width of all elements to 100%, I noticed that I am getting a horizontal scroll bar. I have tried troubleshoot ...

What is the proper way to structure the ng-options syntax in AngularJS?

I received an array from a REST service and I am attempting to generate a dropdown menu based on that data. Check out the jsfiddle example here $scope.reasons = [{ "languageLanguageId": { "languageId": 1, "lastUpdate": "2015-05-08T11:14:00+03:00" ...

When attempting to add or store data in MongoDB, it triggers a 500 server error

Greetings, I am currently working on developing a CRUD app using the MEAN stack. The Express application loads successfully and retrieves the "contactlist" collection from the database. However, when attempting to make a POST request to "/api/contacts", an ...