What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to achieve this?

const fetchAndMeasureDuration = ClientFunction(() => {
  console.time("timer1");
  const fetchData = () => fetch('https://xxxxxx',
    {method : 'GET',
      headers:{
        hash: 'xxxxx',
        id: 'xxxxxxxxc'
      }
    })
    .then(response => response.json())
    .then(data => {
      let duration = console.timeEnd("timer1");
      console.log(duration);
    });
  return fetchData();
});



test('test', async t => {
  await fetchAndMeasureDuration();
  console.log(duration)?????
});

Answer №1

Issue number one: console.timeEnd does not have a return value; it simply prints the elapsed time to the console. It is recommended to use performance.now() or just Date instead.

Further, you should return the duration from the last then block in your code snippet.

const makeApiCall = ClientFunction(() => {
  const start = new Date().getTime();
  const testLocation = () => fetch('https://xxxxxx',
    {method : 'GET',
      headers:{
        hash: 'xxxxx',
        id: 'xxxxxxxxc'
      }
    })
    .then(response => response.json())
    .then(data => {
       const end = new Date().getTime();
       return end - start;
    });
  return testLocation();  // This returns a Promise<number>
});



test('test', async t => {
  const duration = await makeApiCall();
  console.log(duration)?????
});

Answer №2

If you want to test APIs using TestCafe, consider using the t.request method for a structured approach.

fixture `API Testing`;

test('Basic API Test', async t => {
    const startTime = Date.now();

    const response = await t.request('https://jsonplaceholder.typicode.com/comments');
    const duration = Date.now() - startTime;

    console.log(`Request took ${duration}ms to complete`); // Request took 336ms to complete
    await t.expect(response.status).eql(200);
});

Keep in mind that the actual execution time of a request may vary due to factors like the processing of the TestCafe command and messaging overheads. Use this timing as an estimate rather than an exact measure of performance. Additionally, refer to the timeout option for more control over request timeouts.

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

What a great method to execute a button click within the same button click using jQuery!

Here's an example of code that attempts to make an ajax call when a user clicks a button. If the ajax call fails, the button should be reclicked. I've tried this code below, but it doesn't seem to work. $("#click_me").click(function(){ ...

Upgrading to Angular 2: Utilizing ElementRef in ES5

Currently, I am facing a challenge in creating an Attribute directive for Angular 2 that would allow me to set multiple default HTML attributes using a single custom attribute. My intention is to apply this directive specifically to the input element. Howe ...

Contrasting gatsby-theme-material-ui and gatsby-plugin-material-ui

I'm in the process of creating a website using Gatsby, and I'd like to incorporate Material UI, but I'm unsure about which plugin I should use. Here are my questions: What is the difference between these two options, and how can I integra ...

Formatting specific elements within an array

I am working with an array of names, some of which are repeated. These names are then split in half and displayed as li. One thing I am struggling to figure out is how to style the name Joeyc with text-decoration: line-through; on all instances of .book w ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...

I encountered an issue while trying to integrate react-alert into my React application. An Uncaught Error was thrown, stating that objects are not valid as a React

I encountered the following error: react-dom.development.js:14748 Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, render}). If you meant to render a collection of children, use an array instead. in Unknown (c ...

What could be causing the lack of data with 'react-hook-form'?

I have encountered an issue while working with react-native and using 'react-hook-forms' for creating dynamic forms. The problem is that the data object returned is empty, even though it should contain the values entered in the input fields. When ...

I encountered the error message "TypeError: e is undefined" while attempting to make an ajax call

My goal is to showcase a website's content using file_get_contents in a PHP script and ajax on the front-end. I am able to display the entire page successfully, but when attempting to only show a certain number of images, I encounter the "TypeError: e ...

How do I execute a Next.js script that utilizes `fs` and `sharp` during development with Webpack?

I'm working on creating a basic GIFPlayer that displays a GIF when the play button is clicked, and shows a PNG otherwise: <img className="w-full h-full" src={isPlaying ? gifPath : imgPath} alt={pic.alt} /> Since I only have a GIF file ...

Ways to display the hidden element using AngularJS

I want to show the information of "[6] Peter who is 95 years old" in a hidden text box, which should only appear when the button <button ng-click="show_id(friend.id)">get my id</button> is clicked. The name should be displayed using the ng-mode ...

What is the best way to automatically adjust the size of this HTML Menu to match the width of its

I am in the process of converting a Drupal 6 theme to Drupal 7 and I'm encountering some difficulties with this particular section. Below is the HTML code snippet: <ul id="nav" class=" scaling-active scaling-ready"> <li><a href="/demos ...

Discovering the geometric boundaries of a body of text

Seeking help with determining the geometric bounds of text inside hyperlinks in an InDesign document. I've tried to do this using ExtendScript but haven't had any luck. // Loop through and export hyperlinks in the document for (k = 0; k < myD ...

Tips on inserting JS code into React component

I seem to be struggling with integrating my JS code into a React component. I attempted it, but unfortunately made a mess of things. Can anyone provide guidance on how to properly accomplish this? mycomponent.js import React from "react"; import Navbar ...

Is it considered acceptable to retrieve the action payload in mapDispatchToProps in a React/Redux setup?

In my MediaUpload component, I have a mapDispatchToProps function that handles file uploads. When a file is added, the onChange handler triggers two actions: creating new media entries for the files and updating the form data in the state with the generate ...

How to access and retrieve selected checkbox values using jQuery

<form id="myform"> <input type='checkbox' name='foo[]' value='1'> <input type='checkbox' name='foo[]' checked='true' value='2' > <input type='checkbox' ...

What kind of mischief can be wreaked by a malicious individual using JavaScript?

My mind has been consumed by thoughts about the safety of my projects, especially when it comes to password recovery. On the password recovery page, users must fill out a form with valid data and complete a recaptcha test for security. To enhance user ex ...

Is there a way to modify the domain of an iFrame's scr based on the parent window's URL?

Is there a way to dynamically change the scr="" attribute of an iFrame based on the current URL of the window? The goal is to have different values for the scr attribute depending on the parent window's URL. For example, if the parent window's UR ...

JavaScript utilizing an API to retrieve specific data values

Below is some API Data that I have: [ { "symbol": "AAPL", "name": "Apple Inc.", "price": 144.98, "changesPercentage": -1.22, "change": -1.79, ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

`The steps to retrieve XML response data from an API request`

When using axios to make an API request, how can I receive data in XML format? For example: axios.get(/* URL */).then(response => {/* How do I retrieve the XML data? */}).catch(err => {/* result */}); ...